Presentation is loading. Please wait.

Presentation is loading. Please wait.

Vectors.

Similar presentations


Presentation on theme: "Vectors."— Presentation transcript:

1 Vectors

2 Vectors Vectors are containers of objects of the same type that are stored contiguously in memory. In the <vector> library. Syntax: vector<double> vect(10); // initialize vector of 10 doubles.

3 Example Vector Usage vector<int> v(10); v.push_back(4);
v.pop_back(); v.push_back(1); cout << v[0] << v[1];

4 Vector Operations Assume that v is a vector.
- v.front() // return the first element - v.back() // return the last element - v[i] // return the element at index i - v.at(i) // return the element at index i - v.push_back(x) // add element x to the end, increase size if necessary - v.pop_back() // remove the element, reduce size by 1

5 Print a Vector void printVec(const vector<int> &vec) {
for (int i=0; i < vec.size(); i++) cout << vec.at(i) << “ “; cout << “\n”; }

6 Out of Bounds Errors Accessing a vector outside of the allocated space leads to undefined behavior. vector<int> vec; for(int i=0; i<5; i++) vec.push_back(i*2+1); cout << vec.at(5);

7 Size vs. Capacity v.size() is the number of elements in v
v.capacity() is the number of elements that can be stored in v in the space that is currently allocated

8 Insert into a vector Since a vector is stored contiguously in memory, if we want to insert at a specific position, we need to shift everything that comes after it over 1 position. void insert(vector<int> &vec, int pos, int x) { int n = vec.size(); vec.push_back(0); for (int i = n; i > pos; i--) vec[i] = vec[i-1]; vec[pos] = x; }


Download ppt "Vectors."

Similar presentations


Ads by Google