std::vector resize downward

Calling resize() with a smaller size has no effect on the capacity of a vector. It will not free memory. The standard idiom for freeing memory from a vector is to swap() it with an empty temporary vector: std::vector<T>().swap(vec);. If you want to resize downwards you’d need to copy from your original vector into a … Read more

Why is calling vector.reserve(required + 1) faster than vector.reserve(required)?

I made the following modification to the program: size_t a = getenv(“A”) ? 1 : 0; void f(std::vector<Class> const & values) { … container.reserve(values.size() + a); … } Now the performance is same (fast) regardless if a is 0 or 1. The conclusion must be that the reservation of an extra item has no performance … Read more

How can I get the depth of a multidimensional std::vector at compile time?

A classic templating problem. Here’s a simple solution like how the C++ standard library does. The basic idea is to have a recursive template that will count one by one each dimension, with a base case of 0 for any type that is not a vector. #include <vector> #include <type_traits> template<typename T> struct dimensions : … Read more

What is the memory layout of vector of arrays?

Arrays do not have any indirection, but just store their data “directly”. That is, a std::array<int, 5> literally contains five ints in a row, flat. And, like vectors, they do not put padding between their elements, so they’re “internally contiguous”. However, the std::array object itself may be larger than the set of its elements! It … Read more

Initialisation of static vector

In C++03, the easiest way was to use a factory function: std::vector<int> MakeVector() { std::vector v; v.push_back(4); v.push_back(17); v.push_back(20); return v; } std::vector Foo::MyVector = MakeVector(); // can be const if you like “Return value optimisation” should mean that the array is filled in place, and not copied, if that is a concern. Alternatively, you … Read more

Set std::vector to a range

You could use std::iota if you have C++11 support or are using the STL: std::vector<int> v(14); std::iota(v.begin(), v.end(), 3); or implement your own if not. If you can use boost, then a nice option is boost::irange: std::vector<int> v; boost::push_back(v, boost::irange(3, 17));