我要求用户输入大小和数组,但是当我打印矢量时,它仅显示'0'作为输出
I am asking user to enter the size and array but when I am printing the vector it shows '0' only as output
我声明了一个向量并尝试输入大小和值并打印它
#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);
相关文章:
- 为什么在C的循环中使用printf的Rust代码不显示输出,而在C++的循环中显示std::cout
- C++ 构造函数未显示输出
- 显示C++输出而不返回值
- 为什么输出窗口上没有显示输出?
- 为什么我的代码块上没有显示输出?
- C++ 程序不显示输出
- isPalindrome不显示输出,isPalindrome函数未使用字符串输入作为字符串参数进行测试
- 如何从amd gpus的显示输出中获取图像数据
- 插入了 C++ 数组字符串数据,但在显示输出时不显示
- 程序不会在必须时结束并显示输出
- 为什么我的前缀中缀代码不显示输出
- 函数显示输出和输入时出现问题
- 为什么我的程序多次显示输出
- 二进制搜索 - 代码编译并运行后不显示输出
- 字符串流未显示输出
- 为什么当我使用 cout 显示输出时,必须将按位运算符(例如 &,|,等)括在括号中?
- 这段代码可编译,但在visualstudio2015社区中运行(c++)时不显示输出
- Jupyter笔记本未显示C 输出(COUT)
- 尝试拆分循环链表.显示输出但崩溃.在 IDEone 中显示运行时错误
- Q未显示输出