3

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?

krsteeve
  • 1,796
  • 4
  • 19
  • 29
jgyou
  • 465
  • 8
  • 19

2 Answers2

1

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.

Chad
  • 17,081
  • 2
  • 40
  • 60
  • Thanks! I guess I could have guessed the answer by reading the "duplicate" questions :). I was confused there, didn't realize the copy constructor was bound to be called. I threw a shrink_to_fit() call in there to make sure vec_of_vec.back() is always a tight fit, regardless of the implementation. – jgyou Aug 15 '13 at 20:02
  • Yeah, I didn't really feel this was a duplicate, you had a very specific question that wasn't immediately obvious by reading the duplicates and their answers. – Chad Aug 15 '13 at 20:51
0

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

Paul Evans
  • 26,111
  • 3
  • 30
  • 50