« Inbuilt vector
- Vectors are inbuilt dynamic arrays. We don't need to define size at the beginning.
- Vectors are template array.
- 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
- Initially capacity will come as 0. Actually underlying array is null at the beginning.
- In
push_back
method current capacity will be seen whether we need to increase capacity or not. 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.cout << v[4] << endl;
This won't throw error even if the position has garbage value.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_MIN11#include <unordered_map>12using namespace std;13int main()14{15 vector<int> *vp = new vector<int>(); // dynamic allocation16 vector<int> v; // static allocation1718 for (int i = 0; i < 100; i++)19 {20 cout << v.capacity() << " : " << v.size() << endl; // initially capacity will come as 0. Actually21 // underlying array is null at the beginning22 v.push_back(i + 1);23 }2425 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 about2930 v[1] = 100;3132 v[3] = 10002;33 v[4] = 500; // we do directly this then vector won't be thinking about space and wether capacity needs to34 // be increased or not35 // it might happen that we are not writing to the memory alloted to the array. The memory where we might36 // be writing might not belong to us also3738 cout << v[0] << endl;39 cout << v[1] << endl;40 cout << v[2] << endl;41 cout << v[3] << endl;42 cout << v[4] << endl;4344 v.push_back(40); // don't use [] for inserting elements. Use it for getting value or updating the value45 v.push_back(50); // these will overwrite above values as for push_back still last element is at 2nd position4647 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 value5354 cout << "Vector size:" << v.size() << endl;5556 cout << v.at(2) << endl;57 cout << v.at(6) << endl; // this will throw error out of range5859 return 0;60}