Question

I was wondering if the capacity carries over when one pushes a vector onto a vector of vectors.

Say i have a code that looks like

std::vector< std::vector< int > >  vec_of_vec;
std::vector< int > tmp;

for (int i = 0 ; i < 100; ++i) {
   foo(tmp,i); // fills tmp with an arbitrary number of ints, different for each i.
   vec_of_vec.push_back(tmp);
   tmp.clear();
}

Now, since .clear() does not reduce capacity, if one particular instance of tmp is smaller than tmp.capacity(), will tmp.capacity() shrink to fit tmp.size() once it is pushed back onto vec_of_vec? i.e. which constructor does push_back calls, and is capacity modified in the process?

Was it helpful?

Solution

The capacity of the item pushed back vec_of_vec.back(), is implementation defined.

However, since tmp is copied into vec_of_vec (using the copy constructor), the original tmp object's capacity is unchanged in the vec_of_vec.push_back() call.

OTHER TIPS

push_back copies it's argument into vec_of_vec so tmp no longer references what's in vec_of_vec so it's the copy constructor that's called

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top