在 C++ 中,向量函数 push_back 会增加空数组的大小吗? [英] In C++, will the vector function push_back increase the size of an empty array?

查看:32
本文介绍了在 C++ 中,向量函数 push_back 会增加空数组的大小吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

快速提问.假设我声明了一个大小为 20 的向量.然后我想使用 push_back 向它添加几个整数.

Quick question. Let's say I declare a vector of size 20. And then I want to add a few integers to it using push_back.

vector<int> myVector(20);
myVector.push_back(5);
myVector.push_back(14);

我的向量的容量现在是 22,还是仍然是 20?是否分别将 5 和 14 添加到索引 [19] 和 [20] 中?还是在 [0] 和 [1]?

Is the capacity of my vector now 22, or is it still 20? Were 5 and 14 added to indices [19] and [20], respectively? Or are they at [0] and [1]?

推荐答案

在这些语句之后,它的容量是实现定义的.(请注意,这与其大小不同.)

After those statements its capacity is implementation-defined. (Please note that is different from its size.)

vector<int> myVector(20);

这将创建一个填充了 20 个 0 的向量.它的大小正好是二十,它的容量至少是二十.是否正好是 20 是实现定义的;它可能有更多(实际上可能没有).

This creates a vector filled with twenty 0's. Its size is twenty, exactly, and its capacity is at least twenty. Whether or not it's exactly twenty is implementation-defined; it may have more (probably not, in practice).

myVector.push_back(5);

此后,数组的第 21 个元素为 5,容量再次由实现定义.(如果容量之前正好是 20,现在以未指定的方式增加.)

After this, the twenty-first element of the array is 5, and the capacity is once again implementation-defined. (If the capacity had been exactly twenty before, it is now increased in an unspecified manner.)

myVector.push_back(14);

同样,现在数组的 20 秒元素是 14,容量是实现定义的.

Likewise, now the twenty-second element of the array is 14, and the capacity is implementation-defined.

如果你想保留空间,但不想插入元素,你可以这样做:

If you want to reserve space, but not insert elements, you'd do it like this:

vector<int> myVector;
myVector.reserve(20); // capacity is at least twenty, guaranteed not
                      // to reallocate until after twenty elements are pushed

myVector.push_back(5); // at index zero, capacity at least twenty.
myVector.push_back(14); // at index one, capacity at least twenty.

这篇关于在 C++ 中,向量函数 push_back 会增加空数组的大小吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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