vector::operator[]

I was not understanding vector::operator[] functionality. I was assuming I can do an assignment as shown in code below. But the size of array was not updated after adding elements to it. Changing it to push_back works, any hint on what I could be doing wrong?

1
2
3
4
5
6
7
8
9
10
    cin>>count1>>count2; //Get the count of 2 lines
    a.reserve(count1);
    b.reserve(count2);
    for(int i=0;i<count1;i++){
        cin>>temp;
        cout<<"Temp is"<<temp<<endl;
        a[i]=temp;
        cout<<"a[i] is"<<a[i]<<endl;
    }
    cout<<"a size is "<<a.size()<<endl;
[] does not add elements, it merely accesses elements that already exist.

If you try to access an element that doesn't exist (ie: an out of bounds element), then the behavior is undefined.


If you want to add new elements to a vector, you can call resize(), or you can use push_back(), or you can use insert().
Topic archived. No new replies allowed.