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

2023-08-28C/C++开发问题
5

本文介绍了我要求用户输入大小和数组,但是当我打印矢量时,它仅显示“0"作为输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

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

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.

这篇关于我要求用户输入大小和数组,但是当我打印矢量时,它仅显示“0"作为输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

无法访问 C++ std::set 中对象的非常量成员函数
Unable to access non-const member functions of objects in C++ std::set(无法访问 C++ std::set 中对象的非常量成员函数)...
2024-08-14 C/C++开发问题
17

从 lambda 构造 std::function 参数
Constructing std::function argument from lambda(从 lambda 构造 std::function 参数)...
2024-08-14 C/C++开发问题
25

STL BigInt 类实现
STL BigInt class implementation(STL BigInt 类实现)...
2024-08-14 C/C++开发问题
3

使用 std::atomic 和 std::condition_variable 同步不可靠
Sync is unreliable using std::atomic and std::condition_variable(使用 std::atomic 和 std::condition_variable 同步不可靠)...
2024-08-14 C/C++开发问题
17

在 STL 中将列表元素移动到末尾
Move list element to the end in STL(在 STL 中将列表元素移动到末尾)...
2024-08-14 C/C++开发问题
9

为什么禁止对存储在 STL 容器中的类重载 operator&amp;()?
Why is overloading operatoramp;() prohibited for classes stored in STL containers?(为什么禁止对存储在 STL 容器中的类重载 operatoramp;()?)...
2024-08-14 C/C++开发问题
6