1// CPP program to create an empty vector
2// and push values one by one.
3#include <vector>
4
5using namespace std;
6int main()
7{
8 // Create an empty vector
9 vector<int> vect;
10 //add/push an integer to the end of the vector
11 vect.push_back(10);
12 //to traverse and print the vector from start to finish
13 for (int x : vect)
14 cout << x << " ";
15
16 return 0;
17}
1// First include the vector library:
2#include <vector>
3
4// The syntax to create a vector looks like this:
5std::vector<type> name;
6
7// We can create & initialize "lol" vector with specific values:
8std::vector<double> lol = {66.666, -420.69};
9
10// it would look like this: 66.666 | -420.69
1#include <vector>
2
3int main() {
4 std::vector<int> v;
5 v.push_back(10); // v = [10];
6 v.push_back(20); // v = [10, 20];
7
8 v.pop_back(); // v = [10];
9 v.push_back(30); // v = [10, 30];
10
11 auto it = v.begin();
12 int x = *it; // x = 10;
13 ++it;
14 int y = *it; // y = 30
15 ++it;
16 bool is_end = it == v.end(); // is_end = true
17
18 return 0;
19}
1#include <iostream>
2#include <vector>
3
4#define M 3
5#define N 4
6
7int main()
8{
9 // specify default value to fill the vector elements
10 int default_value = 1;
11 // first initialize a vector of ints with given default value
12 std::vector<int> v(N, default_value);
13 // Use above vector to initialize the two-dimensional vector
14 std::vector<std::vector<int>> matrix(M, v);
15
16 return 0;
17}
18
1Vectors are sequence container that can change size. Container is a objects
2that hold data of same type. Sequence containers store elements strictly in
3linear sequence.
4
5Vector stores elements in contiguous memory locations and enables direct access
6to any element using subscript operator []. Unlike array, vector can shrink or
7expand as needed at run time. The storage of the vector is handled automatically.
8
9To support shrink and expand functionality at runtime, vector container may
10allocate some extra storage to accommodate for possible growth thus container
11have actual capacity greater than the size. Therefore, compared to array, vector
12consumes more memory in exchange for the ability to manage storage and grow
13dynamically in an efficient way.
14
15Zero sized vectors are also valid. In that case vector.begin() and vector.end()
16points to same location. But behavior of calling front() or back() is undefined.