Nice way to append a vector to itself

Wow. So many answers that are close, none with all the right pieces. You need both resize (or reserve) and copy_n, along with remembering the original size. auto old_count = xx.size(); xx.resize(2 * old_count); std::copy_n(xx.begin(), old_count, xx.begin() + old_count); or auto old_count = xx.size(); xx.reserve(2 * old_count); std::copy_n(xx.begin(), old_count, std::back_inserter(xx)); When using reserve, copy_n is … Read more

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

The rate at which the capacity of a vector grows is implementation dependent. Implementations almost invariably choose exponential growth, 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 vector’s capacity is grown the elements need … Read more

Correct way to work with vector of arrays

You cannot store arrays in a vector or any other container. The type of the elements to be stored in a container (called the container’s value type) must be both copy constructible and assignable. Arrays are neither. You can, however, use an array class template, like the one provided by Boost, TR1, and C++0x: std::vector<std::array<double, … Read more

How to shuffle a std::vector?

From C++11 onwards, you should prefer: #include <algorithm> #include <random> auto rng = std::default_random_engine {}; std::shuffle(std::begin(cards_), std::end(cards_), rng); Live example on Coliru Make sure to reuse the same instance of rng throughout multiple calls to std::shuffle if you intend to generate different permutations every time! Moreover, if you want your program to create different sequences … Read more