保留后填充[重复]后std :: vector大小不会更新

时间:2023-02-09 18:13:52

This question already has an answer here:

这个问题在这里已有答案:

I need to fill a vector in with particular values. I find that the below code works, except in that a.size() fails to change from 0. Adding a resize call after I put in the elements takes almost twice as long. It seems there should be an O(1) way to update the size, since I don't need to change any elements. Is there? Should I just not bother?

我需要用特定值填充向量。我发现下面的代码工作,除了a.size()无法从0更改。在我放入元素后添加调整大小调用需要几乎两倍的时间。似乎应该有一种O(1)方式来更新大小,因为我不需要更改任何元素。在那儿?我应该不打扰吗?

#include <iostream>
#include <vector>
#include <math.h>

using namespace std;

int main()
{
  int n = 1e9;
  vector<float> a;
  a.reserve(n);
  for (int i=0; i<n; i++)
    a[i] = i;

  cout << a[2]; //successfully prints as 1
  cout << a.size(); //confusingly prints as 0
}

Edit: this is not a duplicate, as the linked question does not address benchmarking. It simply asks the difference in reserve and resize, which I am not asking about. This code works, and fast, but has the ugly side effect of leaving size() "incorrect."

编辑:这不是重复,因为链接的问题不涉及基准测试。它只是询问保留和调整大小的差异,我没有询问。这段代码很有效,但是留下大小()“不正确”的副作用很难看。

1 个解决方案

#1


2  

std::vector::reserve() is not for creating elements. To create elements, you can use std::vector::resize().

std :: vector :: reserve()不用于创建元素。要创建元素,可以使用std :: vector :: resize()。

Try this:

尝试这个:

#include <iostream>
#include <vector>
#include <math.h>

using namespace std;

int main()
{
  int n = 1e9;
  vector<float> a;
  a.resize(n);
  for (int i=0; i<n; i++)
    a[i] = i;

  cout << a[2];
  cout << a.size();
}

#1


2  

std::vector::reserve() is not for creating elements. To create elements, you can use std::vector::resize().

std :: vector :: reserve()不用于创建元素。要创建元素,可以使用std :: vector :: resize()。

Try this:

尝试这个:

#include <iostream>
#include <vector>
#include <math.h>

using namespace std;

int main()
{
  int n = 1e9;
  vector<float> a;
  a.resize(n);
  for (int i=0; i<n; i++)
    a[i] = i;

  cout << a[2];
  cout << a.size();
}