gnomezgrave

std::vector example

Apr 23rd, 2018
134
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.50 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector> // we should include vector before using it.
  3.  
  4. using namespace std;
  5.  
  6. int main()
  7. {
  8.     // creates a new vector. "std::" is not required if we use "using namespace std;"
  9.     // Note that we have to pass int within < > to denote the type of the data
  10.     // it is going to hold
  11.     // These type of classes are called "template classes"
  12.     std::vector<int> myVector;
  13.    
  14.     myVector.push_back(10); // inserts an elemet
  15.     myVector.push_back(9);
  16.    
  17.     for ( int i = 0 ; i < 10 ; i++ )
  18.     {
  19.         myVector.push_back( i * 5 );
  20.     }
  21.    
  22.    cout << "Size : " << myVector.size() << endl;  // print the size of the vector
  23.    
  24.    /*
  25.     To iterate through the elements of a vector (or other std containers),
  26.     we use iterator defined inside that class itself.
  27.     the begin() and end() returns the respective ends of the container.
  28.    */
  29.    
  30.    // start the iteration from the begining
  31.    std::vector<int>::iterator itr = myVector.begin();
  32.    
  33.    // iterate untin the iterator hits the end of the container
  34.    for ( ; itr != myVector.end(); itr++ )
  35.    {
  36.        int val = *itr; // * dereferences the iterator and returns the actual value.
  37.        cout << "Value : " << val << endl;
  38.    }
  39.    
  40.    cout << endl;
  41.    
  42.    // we can access vector elements by index as well.
  43.    for ( int i = 0; i < myVector.size(); i++ )
  44.    {
  45.        int val = myVector[i];
  46.        cout << "Index : " << i << "  " << "Value : " << val << endl;
  47.    }
  48.    
  49.    
  50.    
  51.    return 0;
  52. }
Advertisement
Add Comment
Please, Sign In to add comment