So I have a class wrapping a vector which has the invariant that vec.capacity() > vec.size()
so I can always (temporarily) emplace_back one more element without reallocation. My first idea was to call vec.reserve(vec.size() + 1)
for every insertion, but this is inefficient as seen in this stackoverflow thread, and insert is called very often. (So is pop_back, therefore the maximal number of elements is way lower than the amounts of insert calls.)
My current implementation simplified looks something like this:
#include <vector>
template<typename T>
class VecWrapper {
private:
std::vector<T> vec;
public:
[[nodiscard]] auto insert(T new_element)
{
vec.emplace_back(std::move(new_element));
if (vec.capacity() == vec.size()) {
vec.emplace_back(vec.back());
vec.pop_back();
}
}
};
Is there a less awkward way to trigger a capacity expansion of the vector according to the implementation defined strategy? Note that T is not necessarily default constructible.