How does the capacity of std::vector grow automatically? What is the rate?

The rate at which the capacity of a vector grows is required by the standard to be exponential (which, IMHO, is over-specification). The standard specifies this in order to meet the amortized constant time requirement for the push_back operation. What amortized constant time means and how exponential growth achieves this is interesting. Every time a … Read more

Remove first N elements from a std::vector

Use the .erase() method: // Remove the first N elements, and shift everything else down by N indices myvec.erase(myvec.begin(), myvec.begin() + N); This will require copying all of the elements from indices N+1 through the end. If you have a large vector and will be doing this frequently, then use a std::deque instead, which has … Read more

Correct way to initialize std::vector data member

See http://en.cppreference.com/w/cpp/language/default_initialization Default initialization is performed in three situations: when a variable with automatic storage duration is declared with no initializer when an object with dynamic storage duration is created by a new-expression without an initializer when a base class or a non-static data member is not mentioned in a constructor initializer list and that … Read more

Is there a standard way of moving a range into a vector?

You use a move_iterator with insert: v1.insert(v1.end(), make_move_iterator(v2.begin()), make_move_iterator(v2.end())); The example in 24.5.3 is almost exactly this. You’ll get the optimization you want if (a) vector::insert uses iterator-tag dispatch to detect the random-access iterator and precalculate the size (which you’ve assumed it does in your example that copies), and (b) move_iterator preserves the iterator category … Read more

std::vector (ab)uses automatic storage

There is no limit on how much automatic storage any std API uses. They could all require 12 terabytes of stack space. However, that API only requires Cpp17DefaultInsertable, and your implementation creates an extra instance over what is required by the constructor. Unless it is gated behind detecting the object is trivially ctorable and copyable, … Read more

Performance issue for vector::size() in a loop in C++

In theory, it is called each time, since a for loop: for(initialization; condition; increment) body; is expanded to something like { initialization; while(condition) { body; increment; } } (notice the curly braces, because initialization is already in an inner scope) In practice, if the compiler understands that a piece of your condition is invariant through … Read more