简体   繁体   English

push_back()总是会增加向量的大小吗?

[英]Does push_back() always increase a vector's size?

I have a piece of code which creates a std::vector<T> with a known size: 我有一段代码创建一个已知大小的std :: vector <T>:

std::vector<T> vectorOfTs(n);

Does calling push_back increase the size to n+1? 调用push_back会将大小增加到n + 1吗?

vectorOfTs.push_back(T());

Yes; 是; note that vector<T>.capacity() is different from vector<T>.size() . 注意, vector<T>.capacity()是从不同的vector<T>.size() The latter denotes the number of elements currently in the vector while the former represents the number of items that fit in the space currently allocated for the vector's internal buffer. 后者表示当前在向量中的元素数,而前者表示适合当前为向量的内部缓冲区分配的空间的项数。

Almost. 几乎。 If there are no exceptions, then size() will increment. 如果没有异常,则size()将递增。

push_back(T()) could also throw an exception at various stages: see here , or summarily: push_back(T())也可以在各个阶段抛出异常:请参阅此处或概括:

  • T() construction, in which case no call to push_back takes place, and size() is unaffected T()构造,在这种情况下不会发生对push_back调用,并且size()不受影响

  • if the vector needs to increase the capacity, that may throw, in which case size() is unaffected 如果vector需要增加容量,那可能会抛出,在这种情况下size()不受影响

  • the vector element will be copy or move constructed using std::allocator_traits<A>::construct(m, p, v); vector元素将使用std::allocator_traits<A>::construct(m, p, v);进行复制或移动构造std::allocator_traits<A>::construct(m, p, v); , if A is std::allocator<T> , then this will call placement- new , as by ::new((void*)p) T(v) : if any of this throws the vector 's size() is unaffected, ****unless*** ,如果Astd::allocator<T> ,那么这将调用placement- new ,如::new((void*)p) T(v) :如果其中任何一个抛出vectorsize()是不受影响,****除非***

    • the move constructor isn't noexcept and does throw: in which case the effects are unspecified 移动构造函数不是noexcept并且抛出:在这种情况下,效果是未指定的
  • the vector update's then complete - size() will have incremented and the value will be in the vector (even if T::~T() ) 向量更新然后完成 - size()将递增,值将在vector (即使T::~T()

Yes. 是。 If you instead want to reserve space, call reserve(), eg: 如果您想要预留空间,请调用reserve(),例如:

std::vector<T> vectorOfTs;
vectorOfTs.reserve(n);
// now size() == 0, capacity() >= n

vectorOfTs.push_back(T());
// now size() == 1

Yes. 是。

std::vector<T> vectorOfTs(n);

In the above statement, actually you are constructing 'n' number of new instances of type T (ie default constructor T() would be triggered for each time). 在上面的语句中,实际上你正在构造'n'个类型为T的新实例(即每次都会触发默认构造函数T())。 Now vector vectorOfTs contains n elements. 现在,矢量vectorOfTs包含n个元素。 The following version of the vector constructor would be invoked for the above statement. 将为上述语句调用以下版本的向量构造函数。

explicit vector ( size_type n, const T& value= T(), const Allocator& = Allocator() );

So, when you push back another element into vector, size of vector would be n+1. 因此,当您将另一个元素推回向量时,向量的大小将为n + 1。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM