Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector> // we should include vector before using it.
- using namespace std;
- int main()
- {
- // creates a new vector. "std::" is not required if we use "using namespace std;"
- // Note that we have to pass int within < > to denote the type of the data
- // it is going to hold
- // These type of classes are called "template classes"
- std::vector<int> myVector;
- myVector.push_back(10); // inserts an elemet
- myVector.push_back(9);
- for ( int i = 0 ; i < 10 ; i++ )
- {
- myVector.push_back( i * 5 );
- }
- cout << "Size : " << myVector.size() << endl; // print the size of the vector
- /*
- To iterate through the elements of a vector (or other std containers),
- we use iterator defined inside that class itself.
- the begin() and end() returns the respective ends of the container.
- */
- // start the iteration from the begining
- std::vector<int>::iterator itr = myVector.begin();
- // iterate untin the iterator hits the end of the container
- for ( ; itr != myVector.end(); itr++ )
- {
- int val = *itr; // * dereferences the iterator and returns the actual value.
- cout << "Value : " << val << endl;
- }
- cout << endl;
- // we can access vector elements by index as well.
- for ( int i = 0; i < myVector.size(); i++ )
- {
- int val = myVector[i];
- cout << "Index : " << i << " " << "Value : " << val << endl;
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment