Below in c++ program,
include<iostream>
#include<vector>
using namespace std;
int main()
{
vector<int> numbers;
numbers.push_back(2);
numbers.push_back(10);
numbers.push_back(5);
numbers.push_back(3);
numbers.push_back(7);
numbers[3] = 8;
numbers[5] = 11;
for(int i=0; i<numbers.size(); ++i)
{
cout<<" "<<numbers[i];
}
}
see it on ideone.
here, numbers[3] is working but numbers[5].
It looks like, vector::operator[] doesn’t increase the size of vector like vector::push_back.
so, is this the only difference between these two or something else is there?
push_backcreates a new element on the back with the value specified.operator[]requires the element to be there; it just accesses it. The reason[5]doesn’t work is because you have 5 elements, so your indices range from 0 to 4.Generally, when adding new elements,
push_backis preferred overresize, followed byoperator[]. Only one can be used for reading, though, andoperator[]is also needed to maintain normal array syntax.