« Inbuilt vector

  1. Vectors are inbuilt dynamic arrays. We don't need to define size at the beginning.
  2. Vectors are template array.
  3. Don't use [] for inserting elements. Use it for getting value or updating the value. these will overwrite above values as for push_back still last element is at 2nd position
  4. Initially capacity will come as 0. Actually underlying array is null at the beginning.
  5. In push_back method current capacity will be seen whether we need to increase capacity or not.
  6. v[4] = 500; We do directly this then vector won't be thinking about space and whether capacity needs to be increased or not. It might happen that we are not writing to the memory alloted to the array. The memory where we might be writing might not belong to us also.
  7. cout << v[4] << endl; This won't throw error even if the position has garbage value.
  8. cout << v.at(6) << endl; This will throw error out of range.
1#include <iostream>
2#include <iomanip>
3#include <algorithm>
4#include <string>
5#include <cstring>
6#include <vector>
7#include <cmath>
8#include <map>
9#include <climits>
10// climits for INT_MIN
11#include <unordered_map>
12using namespace std;
13int main()
14{
15 vector<int> *vp = new vector<int>(); // dynamic allocation
16 vector<int> v; // static allocation
17
18 for (int i = 0; i < 100; i++)
19 {
20 cout << v.capacity() << " : " << v.size() << endl; // initially capacity will come as 0. Actually
21 // underlying array is null at the beginning
22 v.push_back(i + 1);
23 }
24
25 v.push_back(10);
26 v.push_back(20);
27 v.push_back(30); // in push current capacity will be seen whether we need to increase capacity or not.
28 // All these things will be thought about
29
30 v[1] = 100;
31
32 v[3] = 10002;
33 v[4] = 500; // we do directly this then vector won't be thinking about space and wether capacity needs to
34 // be increased or not
35 // it might happen that we are not writing to the memory alloted to the array. The memory where we might
36 // be writing might not belong to us also
37
38 cout << v[0] << endl;
39 cout << v[1] << endl;
40 cout << v[2] << endl;
41 cout << v[3] << endl;
42 cout << v[4] << endl;
43
44 v.push_back(40); // don't use [] for inserting elements. Use it for getting value or updating the value
45 v.push_back(50); // these will overwrite above values as for push_back still last element is at 2nd position
46
47 cout << "--------------------------------" << endl;
48 cout << v[0] << endl;
49 cout << v[1] << endl;
50 cout << v[2] << endl;
51 cout << v[3] << endl;
52 cout << v[4] << endl; // this won't throw error even if the position has garbage value
53
54 cout << "Vector size:" << v.size() << endl;
55
56 cout << v.at(2) << endl;
57 cout << v.at(6) << endl; // this will throw error out of range
58
59 return 0;
60}