Question

I'm running very time sensitive code and would need a scheme to reserve more space for my vectors at a specific place in the code, where I can know (approximately) how many elements will be added, instead of having std do it for me when the vector is full.

I haven't found a way to test this to make sure there are no corner cases of std that I do not know of, therefore I'm wondering how the capacity of a vector affects the reallocation of memory. More specifically, would the code below make sure that automatic reallocation never occurs?

code

std::vector<unsigned int> data;
while (condition) {
    // Reallocate here
    // get_elements_required() gives an estimate that is guaranteed to be >= the actual nmber of elements.
    unsigned int estimated_elements_required = get_elements_required(...);
    if ((data.capacity() - data.size()) <= estimated_elements_required) {
        data.reserve(min(data.capacity() * 2, data.max_length - 1));
    }

    ...

    // NEVER reallocate here, I would rather see the program crash actually...
    for (unsigned int i = 0; i < get_elements_to_add(data); ++i) {
        data.push_back(elements[i]);
    }
}

estimated_elements_required in the code above is an estimate that is guaranteed to be equal to, or greater than, the actual number of elements that will be added. The code actually adding elements performs operations based on the capacity of the vector itself, changing the capacity halfway through will generate incorrect results.

Was it helpful?

Solution

Yes, this will work.

From the definition of reserve:

It is guaranteed that no reallocation takes place during insertions that happen after a call to reserve() until the time when an insertion would make the size of the vector greater than the value of capacity().

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top