C++ examples for STL:vector
Exchange the contents of vector 1 and vector 3.
#include <iostream> #include <vector> using namespace std; void show(const char *msg, vector<char> vect); int main() {/* ww w . j a v a 2s .co m*/ // Declare an empty vector that can hold char objects. vector<char> v; // Declare an iterator to a vector<char>. vector<char>::iterator itr; // Obtain an iterator to the start of v. itr = v.begin(); // Declare a reverse iterator. vector<char>::reverse_iterator ritr; // Create another vector that is the same as the first. vector<char> v2(v); show("The contents of v2: ",v2); cout << "\n"; // Create another vector. vector<char> v3; v3.insert(v3.end(), 'X'); v3.insert(v3.end(), 'Y'); v3.insert(v3.end(), 'Z'); show("The contents of v3: ", v3); cout << "\n"; // Exchange the contents of v and v3. cout << "Exchange v and v3.\n"; v.swap(v3); show("The contents of v: ", v); show("The contents of v3: ", v3); cout << "\n"; // Clear v. v.clear(); if(v.empty()) cout << "v is now empty."; return 0; } // Display the contents of a vector<char> by using an iterator. void show(const char *msg, vector<char> vect) { vector<char>::iterator itr; cout << msg; for(itr=vect.begin(); itr != vect.end(); ++itr) cout << *itr << " "; cout << "\n"; }