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

2021-12-26 00:00:00 while-loop vector c++

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

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

电流输出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 中读取的值,而是从 sarr 声明中创建的初始值.

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.

相关文章