Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is capacity copied in a vector?

Tags:

c++

vector

Take the following code:

std::vector<int> a; a.reserve(65536); std::vector<int> b(a);  //NOTE: b is constructed from a  a.reserve(65536); // no reallocation b.reserve(65536); 

Is capacity copied? Will there be a reallocation on the last line? Does the standard say anything about this or is it silent?

like image 405
user6426033 Avatar asked Jun 05 '16 07:06

user6426033


People also ask

Is capacity a vector?

The size of a vector is the number of elements that it contains, which is directly controlled by how many elements you put into the vector. Capacity is the amount of total space that the vector has. Under the hood, a vector just uses an array. The capacity of the vector is the size of that array.

What is capacity in vector in C++?

The C++ function std::vector::capacity() returns the size of allocate storage, expressed in terms of elements. This capacity is not necessarily equal to the size of vector. It can be equal or greater than vector size. The theoretical limit on vector size is given by member max_size.

Does vector erase change capacity?

Note that while capacity() doesn't decrease after the erase, the size() certainly does. It's worth detailing your toolchain when producing a counter-example.


2 Answers

Is capacity copied?

In practice, no. I tested it online in Clang and GCC as well as MSVC and none of them copy the capacity.

Will there be a reallocation on the last line?

If the capacity is less than the argument to reserve (i.e. it doesn't get copied) then yes.

Does the standard say anything about this or is it silent?

No definitions for the copy constructor are provided in vector.cons. Instead we have to look at the container.requirements

X denotes a container class containing objects of type T, a and b denote values of type X, u denotes an identifier, r denotes a non-const value of type X, and rv denotes a non-const rvalue of type X.

X u(a)

X u = a;

Requires: T is CopyInsertable into X (see below).

post: u == a

Now what does it mean for two containers to be equal?

a == b

== is an equivalence relation. equal(a.begin(), a.end(), b.begin(), b.end())

In other words, since it doesn't require capacity to be equal in the comparison, then there's no reason to copy the capacity.

like image 154
uh oh somebody needs a pupper Avatar answered Sep 21 '22 19:09

uh oh somebody needs a pupper


Standard says nothing about preserving capacity when you call copy constructor. So you have no any guarantees about it.

But you can do the following trick, which swap a's and b's state, if you need preserving capacity in the copy only:

 std::vector<int> a;  a.reserve(65536);  std::vector<int> b(a);  b.swap(a); // now b has a's state  assert(b.capacity() == 65536);  
like image 27
AnatolyS Avatar answered Sep 21 '22 19:09

AnatolyS