我要求用户输入大小和数组,但是当我打印矢量时,它仅显示'0'作为输出

I am asking user to enter the size and array but when I am printing the vector it shows '0' only as output

本文关键字:显示 输出 打印 输入 用户 数组 我要      更新时间:2023-10-16

我声明了一个向量并尝试输入大小和值并打印它

#include<iostream>
#include<vector>
using namespace std;
int main()
{
int s;          
cin>>s;                   //taking size of vector
vector <int> arr(s);
int input;
while (cin >> input)
{arr.push_back(input);}     //inserting the values in array
for(int i=0;i<s;i++)
cout<<" "<<arr[i];         //printing the values
}

我的输入 5

1 2 3 4 5

预期产出

1 2 3 4 5

电流输出

0 0 0 0 0

这一行:

vector <int> arr(s);

使arr具有大小s。它将具有s个已默认初始化为 0 的元素。然后你正在这个向量上执行push_back,这会将其他元素添加到向量中。

当您打印出前s个元素时,您看到的不是从cin中读取的值,而是在arr声明中创建的s个初始值。

要解决此问题,要么在声明arr时不要给出大小,要么只使用arr[i] = input;而不是循环中的push_back()

您创建向量的语句不仅创建了它,还用 5 个默认值填充了它。 对于整数,默认值为 0。

vector <int> arr(s);

只需查看std::vector构造函数的所有重载。

你可能不想这样,你想要的是在向量中保留 5 个空格,因为你知道你要推动 5 个值。 你用reserve.

vector <int> arr;
arr.reserve(s);