Cpp Vector


Vectors are a kind of sequence containers. Their elements are ordered following a strict linear sequence.
Unlike regular arrays, storage in vectors is handled automatically, allowing it to be expanded if needed.


Example: Simple example of storing STL strings in a vector. Shows three methods of accessing elements of a vector.

#include <iostream>
#include <vector>
#include <string>
using namespace std;
   vector<string> SS;
   SS.push_back("The number is 10");
   SS.push_back("The number is 20");
   SS.push_back("The number is 30");
   cout << "Loop by index:" << endl;
   int ii;
   for(ii=0; ii < SS.size(); ii++)
      cout << SS[ii] << endl;
   cout << endl << "Constant Iterator:" << endl;
   vector<string>::const_iterator cii;
   for(cii=SS.begin(); cii!=SS.end(); cii++)
      cout << *cii << endl;
   cout << endl << "Reverse Iterator:" << endl;
   vector<string>::reverse_iterator rii;
   for(rii=SS.rbegin(); rii!=SS.rend(); ++rii)
      cout << *rii << endl;
   cout << endl << "Sample Output:" << endl;
   cout << SS.size() << endl;
   cout << SS[2] << endl;
   swap(SS[0], SS[2]);
   cout << SS[2] << endl;
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-Share Alike 2.5 License.