C ++ std :: vector memory / allocation

From a previous question about vector capacitance , Mr. Bailey said:

In current C ++, you are guaranteed that no reallocation occurs after a call to reserve, until the insert is larger than the previous call to reserve. Before a reservation call, or after a reservation call, when the size is between the value of the previous reservation call and the throughput, implementations are allowed to reallocate the earlier ones if they so choose.

So if I understand correctly, to ensure that no reallocation occurs before capacity is exceeded, should I reserve twice? Could you please clarify this?

I am using a vector as a memory stack like this:

std::vector<double> memory;
memory.reserve(size);
memory.insert(memory.end(), matrix.data().begin(), matrix.data().end()); // smaller than size
memory.resize(memory.capacity(), 0);

      

I need to ensure that no reallocation happens in the above.

thank.

ps: I would also like to know if there is a better way to manage the memory stack in a similar non-vector way

+1


source to share


3 answers


I think you are reading this statement incorrectly. The stock is allowed to be set capacity

to a larger amount than you have reserved. The ad-hoc language should allow implementation re-allocation if you reserve more than you last did, but before you reach your current capacity.



+4


source


He redistributes when he needs more. You don't need to reserve twice. It is recommended that you use a reserve if you are investing a lot and you have a good knowledge of the size of what you are holding. It's much faster.



0


source


You don't need to call twice reserve

.

Also, in the code example posted, you only call reserve

once. In reality, the code you insert affects size

vectors. See 23.3.6.2.11 (C ++ 0x FCD) about effects void resize(size_type sz, const T& c);

:

if (sz > size())
    insert(end(), sz-size(), c);
else if (sz < size())
    erase(begin()+sz, end());
else
     ; // do nothing

      

So basically, when you call memory.resize(memory.capacity(), 0)

, you are actually adding on 0

, memory.capacity() - memory.size()

times after your call memory.insert

.

0


source







All Articles