vector::push_back vs vector::operator[](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[]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:vector::push_back 与 vector::operator[]
- 静态初始化顺序失败 2022-01-01
- C++ 协变模板 2021-01-01
- 从python回调到c++的选项 2022-11-16
- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
- STL 中有 dereference_iterator 吗? 2022-01-01
- 近似搜索的工作原理 2021-01-01
- Stroustrup 的 Simple_window.h 2022-01-01
- 如何对自定义类的向量使用std::find()? 2022-11-07
- 使用/clr 时出现 LNK2022 错误 2022-01-01
