Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
261 views
Welcome To Ask or Share your Answers For Others

1 Answer

std::vector::operator[]: "access specified element"

std::vector::push_back: "adds an element to the end"

I'm so amazing at looking at c++ references. You should try it.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...