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
source to share
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
.
source to share