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[]
基础教程推荐
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 从 std::cin 读取密码 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01