简体   繁体   English

控制std :: vector重新分配

[英]Control over std::vector reallocation

By reading the std::vector reference I understood that 通过阅读std::vector引用我明白了

  1. calling insert when the the maximum capacity is reached will cause the reallocation of the std::vector (causing iterator invalidation) because new memory is allocated for it with a bigger capacity. 当达到最大容量时调用insert将导致重新分配std::vector (导致迭代器失效),因为为其分配了更大容量的新内存。 The goal is to keep the guarantee about contiguous data. 目标是保证连续数据的保证。

  2. As long as I stick below the maximum capacity insert will not cause that (and iterators will be intact). 只要我坚持低于最大容量insert就不会导致(并且迭代器将完好无损)。

My question is the following: 我的问题如下:

When reserve is called automatically by insert , is there any way to control how much new memory must be reserved? reserve被自动调用insert ,有没有什么办法来控制多新的内存必须如何保留?

Suppose that I have a vector with an initial capacity of 100 and, when the maximum capacity is hit, I want to allocate an extra 20 bytes. 假设我有一个初始容量为100的向量,当达到最大容量时,我想分配额外的20个字节。

Is it possible to do that? 有可能吗?

You can always track it yourself and call reserve before it would allocate, eg 您可以随时自行跟踪并在分配之前调用预留,例如

static const int N = 20 // Amount to grow by
if (vec.capacity() == vec.size()) {
  vec.reserve(vec.size() + N);
}
vec.insert(...);

You can wrap this in a function of your own and call that function instead of calling insert() directly. 您可以将它包装在您自己的函数中并调用该函数,而不是直接调用insert()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM