Declaration
1 2 3 4 5 6 7 |
vector<int> v; // Size of 100 and initialize all to 0 vector<int> v(100, 0) // Reserve size of 3, to prevent extra complexity for copying v.reserve(3); |
Simple operation
1 2 |
int n; v.push_back(n); |
Fill with something
1 |
fill(v.begin(), v.end(), 101); |
Combine two vectors
1 2 3 |
vector<int> head, tail; head.insert(head.end(), tail.begin(), tail.end()); |
In-place solution for creating object
1 2 3 4 5 6 7 |
class Coord { private: int x, y; public: Coord(int x, int y) : x(x), y(y) {} }; |
Originally, object gets created first in the main stack and then copied to the vector’s memory address
1 2 3 |
vector<Coord>v; Coord tmp(1, 2); v.push_back(tmp); |
In-place object creation can be achieved and save the computing time for copying the object
1 2 |
vector<Coord>v; v.emplace_back(1, 2); // Pass the parameters of the constructor directly |