Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Isn't reserve needed when constructing a std::vector using iterators?

So when I call a constructor of a vector using iterators, i.e.:

template <class InputIterator> vector (InputIterator first, InputIterator last);

I don't seem to have the possibility to ensure that sufficient space is reserved in the underlying array, before the constructor starts adding the elements. Will that imply that there may be resizes of that array during construction, or can I assume that the constructor infers the right size by somehow looking at the "distance" between the iterators and the size of the object? (Not sure if that is possible in all cases?)

like image 942
willem Avatar asked Dec 04 '19 08:12

willem


1 Answers

From the standard, [vector.cons]/10

Complexity: Makes only N calls to the copy constructor of T (where N is the distance between first and last) and no reallocations if iterators first and last are of forward, bidirectional, or random access categories. It makes order N calls to the copy constructor of T and order logN reallocations if they are just input iterators.

That means it's guaranteed that reallocation won't happen if passing forward, bidirectional, or random access itearators, then reserve is not needed for these cases. For input iterators these's no such guarantee.

like image 145
songyuanyao Avatar answered Sep 25 '22 16:09

songyuanyao