我要求用户输入大小和数组,但是当我打印矢量时,它仅显示"0"作为输出 [英] I am asking user to enter the size and array but when I am printing the vector it shows '0' only as output
问题描述
我声明了一个向量,并试图放入大小和值并打印出来
I declared a vector and trying to put size and values and printing it
#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
预期产量
1 2 3 4 5
1 2 3 4 5
电流输出0 0 0 0 0
Current output 0 0 0 0 0
推荐答案
此行:
vector <int> arr(s);
使 arr
的大小为 s
.它将具有已默认初始化为0的 s
个元素.然后您对该向量进行 push_back
,这会将 additional 元素添加到向量.
makes arr
have the size s
. It will have s
elements that have been default-initialized to 0. Then you are doing push_back
on this vector, which adds additional elements into the vector.
当打印出第一个 s
元素时,您看不到从 cin
读取的值,但看到的是 s
个在 arr
的声明中创建的初始值.
When you print out the first s
elements, you are not seeing the values that were read from cin
, but the s
number of initial values created in the declaration of arr
.
要解决此问题,要么在声明 arr
时不给出大小,要么仅使用 arr [i] = input;
而不是 push_back()
.
To fix this, either don't give a size when you declare arr
, or else just use arr[i] = input;
instead of push_back()
in the loop.
这篇关于我要求用户输入大小和数组,但是当我打印矢量时,它仅显示"0"作为输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!