vector::push_back 与 vector::operator[] [英] vector::push_back vs vector::operator[]

查看:47
本文介绍了vector::push_back 与 vector::operator[]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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.

这篇关于vector::push_back 与 vector::operator[]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆