O'Reilly logo

Mastering C++ Programming by Jeganathan Swaminathan

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Vector 

Vector is a quite useful sequence container, and it works exactly as an array, except that the vector can grow and shrink at runtime while an array is of a fixed size. However, the data structure used under the hood in an array and vector is a plain simple built-in C/C++ style array.  

Let's look at the following example to understand vectors better:

#include <iostream>#include <vector>#include <algorithm>using namespace std;int main () {  vector<int> v = { 1, 5, 2, 4, 3 };  cout << "\nSize of vector is " << v.size() << endl;  auto pos = v.begin();  cout << "\nPrint vector elements before sorting" << endl;  while ( pos != v.end() )    cout << *pos++ << "\t";  cout << endl;  sort( v.begin(), v.end() );  pos = v.begin(); cout << "\nPrint vector ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required