C
|
C++
|
Objective-C
|
VC++
|
Win32
|
MFC
|
Java
|
Php
|
Delphi
|
Visual Basic
|
.Net
|
Networking
|
General
|
Games
|
Jobs
|
Javascript
|
Menu
Project Upload
Project Download
Articles
Programs
Search
Solution
pickSourcecode.com
Login
Register
About us
Contact us
Cpp
>
Programs
cpp vector , push_back. pop_back example
#include <iostream>
#include <vector>
using namespace std;
typedef vector<int> intVector;
typedef vector<int>::iterator ivItor;
template<class T, class A>
void
ShowVector(const vector<T, A>& v);
int
main()
{
intVector vInt(5);
// define a vector of integers with 3 elements
cout << "vInt(5)" << "\n";
// assign a value to each element in vInt using subscripts
for
(vector<int>::size_type i = 0; i < vInt.size(); ++i)
vInt[i] = 5 * i;
ShowVector(vInt);
// insert an element
cout << "vInt after insert(vInt.begin() + 1, 50)\n";
ivItor itor = vInt.insert(vInt.begin() + 1, 50);
ShowVector(vInt);
cout << "Current element is " << *itor << "\n\n";
// insert 5 element
cout << "vInt after insert(vInt.end(), 5, 30)\n";
vInt.insert(vInt.end(), 5, 30);
ShowVector(vInt);
// erase one element from vInt
cout << "vInt after erase one element\n";
vInt.erase(vInt.begin() + 3);
ShowVector(vInt);
// erase three element from vInt
cout << "vInt after erase three element\n";
vInt.erase(vInt.begin() + 3, vInt.begin() + 6);
ShowVector(vInt);
// insert several elements from another vector
intVector vInt2(2);
cout << "vInt2" << "\n";
ShowVector(vInt2);
cout << "vInt2 after insert from vInt\n";
vInt2.insert(vInt2.begin() + 1, vInt.begin() + 1, vInt.begin() + 3);
ShowVector(vInt2);
// add an element at the end of vInt2
cout << "vInt2 after push_back()\n";
vInt2.push_back(100);
ShowVector(vInt2);
// remove an element from the end of vInt2
cout << "vInt2 after pop_back()\n";
vInt2.pop_back();
ShowVector(vInt2);
// clear vInt2
cout << "vInt2 cleared\n";
vInt2.clear();
ShowVector(vInt2);
return 0;
}
//
// Display vector properties
//
template<class T, class A>
void
ShowVector(const vector<T, A>& v)
{
cout << "size() = " << v.size() << "\tcapacity() = " << v.capacity() << "\n";
// traverse through the vector using subscripts
cout << "elements:\t";
for
(vector<T, A>::size_type i = 0; i < v.size(); ++i)
cout << v[i] << ", ";
cout << "\n\n";
}
Privacy Policy
|
About Us