【问题标题】:Can std::vector capacity/size/reserve be used to manually manage vector memory allocation?std::vector capacity/size/reserve 可以用来手动管理向量内存分配吗?
【发布时间】:2014-06-12 04:38:22
【问题描述】:

我正在运行对时间非常敏感的代码,并且需要一个方案来在代码中的特定位置为我的向量保留更多空间,在那里我可以(大约)知道将添加多少元素,而不是让 std 做当向量已满时,它给我。

我还没有找到一种方法来测试它以确保没有我不知道的 std 的极端情况,因此我想知道向量的容量如何影响内存的重新分配。更具体地说,下面的代码会确保自动重新分配从不发生吗?

代码

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 上面代码中的估计值保证等于或大于将要添加的实际元素数。实际添加元素的代码是根据向量本身的容量来进行运算的,中途改变容量会产生不正确的结果。

【问题讨论】:

  • 您可能想使用resize(() 而不是reserve()
  • 而且你不只是调用data.reserve(elements_required);,因为......?还是您的意思是 elements_required 实际上是 elements_to_add(此代码的来源是个谜)?
  • @πάνταῥεῖ:他在添加元素时增加了下面的大小。
  • 是的,您可以谨慎使用reserve,以便准确控制何时分配内存。除非您添加超出当前的capacity,否则保证不会被分配。
  • 代码中的elements_to_addelements_requireddata.size()data.capacity()*2 有什么关系?

标签: c++ vector standard-library c++98


【解决方案1】:

是的,这会起作用。

来自reserve的定义:

保证在调用 reserve() 之后发生的插入过程中不会发生重新分配,直到插入会使向量的大小大于 capacity() 的值。

【讨论】:

  • 这是我担心的 iff 部分。当大小 > 90% 的容量或类似情况时,一些假设批量添加和重新分配的启发式方法的可能性。
  • @user3235200:那是非法的,因为他们会破坏用户的指针/引用失效语义。
  • @DeadMG:另一种解释是,您必须在每次push_back 调用之后检查capacity(),如果它没有改变,那么您就知道没有发生重新分配。
  • 我认为这句话中的if 表示if and only if
  • 一般来说,标准确实区分了“如果”和“当且仅当”。然而,对于std::vector::reserve(),标准保证... 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()
猜你喜欢
  • 1970-01-01
  • 2012-03-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-22
  • 1970-01-01
相关资源
最近更新 更多