我正在尝试将值推入向量。但似乎全为0。
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> a;
int size = 5;
int b;
bool g = false; // In different cases I initialise of not
if (!g) a.resize(size); // initialise vector with such code
for (int i = 0; i < size; i++)
{
if (!a.empty())
{
cout << "Type number ";
cin >> b;
a.push_back(b);
cout << "a[" << i << "] = " << a[i] << ", i = " << i << ", b = " << b << endl;
}
}
system("pause");
}
控制台代码
Type number 0
a[0] = 0, i = 0, b = 0
Type number 1
a[1] = 0, i = 1, b = 1
Type number 2
a[2] = 0, i = 2, b = 2
Type number 3
a[3] = 0, i = 3, b = 3
Type number 4
a[4] = 0, i = 4, b = 4
怎么回事?我认为有一个错误,但我无法理解
答案 0 :(得分:3)
如果设置矢量的大小,则它将具有该大小。向后推另一个元素会将添加到向量中,从而增加向量的大小。它不会更改现有元素。
似乎您想使用reserve
来代替,它设置容量(并保留内存),但不设置大小。