vector::push_back 与 vector::operator[]

2021-12-21 00:00:00 operator-keyword vector c++ stl push-back

c++程序下面,

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];
    }
}    

在 ideone 上查看.

在这里,numbers[3] 正在工作,但 numbers[5].
看起来,vector::operator[] 不会像 vector::push_back 那样增加向量的大小.
那么,这是这两者之间的唯一区别还是有其他区别?

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_back 在背面创建一个具有指定值的新元素.operator[] 要求元素在那里;它只是访问它.[5] 不起作用的原因是因为你有 5 个元素,所以你的索引范围从 0 到 4.

push_back creates 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.

通常,在添加新元素时,push_back 优先于 resize,其次是 operator[].但是只有一个可以用于读取,并且还需要operator[]来维护正常的数组语法.

Generally, when adding new elements, push_back is preferred over resize, followed by operator[]. Only one can be used for reading, though, and operator[] is also needed to maintain normal array syntax.

相关文章