如何预留多维向量? [英] How to reserve a multi-dimensional Vector?

查看:40
本文介绍了如何预留多维向量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有向量的向量

vector< vector<int> > bigTable;

bigTable.reserve(5);

澄清我对调整大小和保留的理解.

To clarify my understanding of resize and reserve.

当你对向量使用 push_back 时,你必须在每次使用它时分配内存.所以我的目标是在一边设置一组内存空间,这样它会最便宜.

When you use push_back with vectors, you have to allocate memory each time you use it. So my goal is to set a side a set of memory space so that it will be least expensive.

因此,是否会为上述目标保留帮助?

As such, will reserve help with the above goal?

推荐答案

您不必每次调用 push_back 时都分配内存.向量从给定的容量开始,它只在原始容量用完时分配额外的容量,通常是将之前的容量加倍.仅当您确定需要额外容量时才应保留.您可以使用 capacity 成员检查开始时的容量.所以,是的,调用 reserve 会有所帮助,但前提是您从一开始就知道您确实需要额外的容量.但是,您也可以相信矢量会在需要时增加其容量.

You don't have to allocate memory each time you call push_back. The vector starts off with a given capacity, and it only allocates extra capacity when the original capacity runs out, typically by doubling the previous capacity. You should only reserve if you are sure you are going to need the extra capacity. And you can check how much capacity you start off with using the capacity member. So, yes, a call to reserve can help, but only if you know from the outset that you really need the extra capacity. But you can also trust the vector to increase its capacity if and when it needs it.

在我的特定平台上,当我用 5 个 Foo 元素初始化一个向量时,它的容量为 5.当我添加一个新元素时,容量跳到 10.这不是标准规定的,原来的容量可能远远超过 5.

On my particular platform, when I initialize a vector with 5 Foo elements, it has capacity 5. As I add a new element, the capacity jumps to 10. This is not mandated by the standard, the original capacity could have been much more than 5.

struct Foo {
  long long n;
};

int main() {

  std::vector<Foo> f(5);
  std::cout << f.capacity() << "\n";
  f.push_back(Foo());
  std::cout << f.capacity() << "\n";

}

这篇关于如何预留多维向量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆