Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Vectors
- You can think of vectors as smart arrays. They manage storage allocation for you, expanding
- and contracting the size of the vector as you insert or erase data. You can use vectors much like
- arrays, accessing elements with the [] operator. Such random access is very fast with vectors.
- It’s also fast to add (or push) a new data item onto the end (the back) of the vector. When this
- happens, the vector’s size is automatically increased to hold the new item.
- Member Functions push_back(), size(), and operator[]
- Our first example, VECTOR, shows the most common vector operations.
- // vector.cpp
- // demonstrates push_back(), operator[], size()
- #include <iostream>
- #include <vector>
- using namespace std;
- int main()
- {
- vector<int> v; //create a vector of ints
- v.push_back(10); //put values at end of array
- v.push_back(11);
- v.push_back(12);
- v.push_back(13);
- v[0] = 20; //replace with new values
- v[3] = 23;
- for(int j=0; j<v.size(); j++) //display vector contents
- cout << v[j] << ‘ ‘; //20 11 12 23
- cout << endl;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement