C++ STL vector, swap() code example
Compiler: Visual C++ Express Edition 2005
Compiled on Platform: Windows XP Pro SP2
Header file: Standard
Additional library: none/default
Additional project setting: Set project to be compiled as C++
Project -> your_project_name Properties -> Configuration Properties -> C/C++ -> Advanced -> Compiled As: Compiled as C++ Code (/TP)
Other info: none
To do: Using the C++ swap() to exchange the elements of two vectors in C++ programming
To show: How to use the C++ vector, swap() to exchange the elements of two vectors in C++ programming
// C++ STL vector, swap()
#include <vector>
#include <iostream>
using namespace std;
int main(void)
{
// vector containers
vector <int> vec1, vec2;
unsigned int i;
// push/insert data
vec1.push_back(4);
vec1.push_back(7);
vec1.push_back(2);
vec1.push_back(12);
// print the data and do some operations
cout<<"vec1 vector data: ";
for(i=0; i<vec1.size(); ++i)
cout<<vec1[i]<<' ';
cout<<endl;
// push more data
vec2.push_back(11);
vec2.push_back(21);
vec2.push_back(30);
// print the data
cout<<"vec2 vector data: ";
for(i=0; i<vec2.size(); ++i)
cout<<vec2[i]<<' ';
cout<<endl;
cout<<"The number of elements in vec1 = "<<vec1.size()<<endl;
cout<<"The number of elements in vec2 = "<<vec2.size()<<endl;
cout<<endl;
// do the swapping
cout<<"Operation: vec1.swap(vec2);"<<endl<<endl;
vec1.swap(vec2);
cout<<"The number of elements in v1 = "<<vec1.size()<<endl;
cout<<"The number of elements in v2 = "<<vec2.size()<<endl;
cout<<"vec1 vector data: ";
for(i=0; i<vec1.size(); ++i)
cout<<vec1[i]<<' ';
cout<<endl;
cout<<"vec2 vector data: ";
for(i=0; i<vec2.size(); ++i)
cout<<vec2[i]<<' ';
cout<<endl;
return 0;
}
Output examples:
vec1 vector data: 4 7 2 12
vec2 vector data: 11 21 30
The number of elements in vec1 = 4
The number of elements in vec2 = 3
Operation: vec1.swap(vec2);
The number of elements in v1 = 3
The number of elements in v2 = 4
vec1 vector data: 11 21 30
vec2 vector data: 4 7 2 12
Press any key to continue . . .