vector.reserve() 在 c++14 中的意外行为?

Unexpected behaviour of vector.reserve() in c++14?

我写了一个代码来对整数向量进行排序,发现一个版本工作正常而另一个版本不工作。

版本 1:使用 vector.reserve

#include <bits/stdc++.h>
using namespace std;
int main(void)
{
      ios_base::sync_with_stdio(false);
      vector<int> a;
      a.reserve(4);
      int i = 0;
      while (i < 4)
      {
            cin >> a[i++];
      }
      sort(a.begin(), a.end());
      for (int i :a)
      {
            cout << i << " ";
      }
}
INPUT: 1 5 3 2
OUTPUT:

版本 2:预先定义矢量大小

#include <bits/stdc++.h>
using namespace std;
int main(void)
{
      ios_base::sync_with_stdio(false);
      vector<int> a(4);
      int i = 0;
      while (i < 4)
      {
            cin >> a[i++];
      }
      sort(a.begin(), a.end());
      for (int i :a)
      {
            cout << i << " ";
      }
}
INPUT: 1 5 3 2
OUTPUT: 1 2 3 5

我不太清楚两者之间有什么区别,如果有区别的话什么时候使用哪个。

vector reserve 方法不会更改 vector 的大小,它可能会更改分配的内存量。您仍然无法在第一个示例中的循环中写入索引 0 到 3,因为 vector 的大小仍然为 0。您需要 resize,这也会改变大小。