In C++, a vector is like a dynamic array that can change its size freely and is sometimes referred to as a container. To use vector, you need to include the #include <vector> header file.
Usage
Initialization
int refers to the type of the container, and abc is the name of the container.
//b is a vector, assign the first 3 elements of b to vector a a.assign(b.begin(),b.begin()+3); //a contains 4 elements with value 2 a.assign(4,2); //return the last element of a a.back(); //return the first element of a a.front(); //return the i-th element of a, if a exists a[i]; //clear all elements in a a.clear(); //check if a is empty, return true if empty, false otherwise a.empty(); //delete the last element of vector a a.pop_back(); //delete elements from the first (index 0) to the third element of a, meaning it deletes elements starting from a.begin()+1 (inclusive) up to a.begin()+3 (exclusive) a.erase(a.begin()+1,a.begin()+3); //insert an element with value i at the end of a a.push_back(i); //insert value 5 at the first element position (from index 0) of a a.insert(a.begin()+1,5); //insert 3 numbers, all with value 5, at the first element position (from index 0) of a a.insert(a.begin()+1,3,5); //b is an array, insert the third to the fifth element of b (excluding b+6) at the first element position (from index 0) of a a.insert(a.begin()+1,b+3,b+6); //return the number of elements in a a.size(); //return the total number of elements a can hold in memory a.capacity(); //adjust the existing number of elements in a to 10, deleting excess or filling with random values a.resize(10); //adjust the existing number of elements in a to 10, deleting excess or filling with value 2 a.resize(10,2); //expand the capacity of a to 100 a.reserve(100); //b is a vector, swap all elements between a and b a.swap(b); //b is a vector, comparison operations for vectors also include != >= > <= < a==b;
Common Algorithms
1 2 3 4 5 6 7 8 9
#include<algorithm> //sort the elements in a from a.begin() (inclusive) to a.end() (exclusive) in ascending order sort(a.begin(),a.end()); //reverse the elements in a from a.begin() (inclusive) to a.end() (exclusive), but do not sort. Example: if a contains 1,3,2,4, after reversal it becomes 4,2,3,1 reverse(a.begin(),a.end()); //copy elements from a.begin() (inclusive) to a.end() (exclusive) in a to b, starting at position b.begin()+1 (inclusive), overwriting existing elements copy(a.begin(),a.end(),b.begin()+1); //search for 10 in elements from a.begin() (inclusive) to a.end() (exclusive) in a, return its position in the vector if found find(a.begin(),a.end(),10);