C++ 如何打印向量?
我一直在研究一种将数字输入向量然后输出的方法,但它总是说向量超出范围,并弹出一个非常奇怪的错误。没有任何编译错误,但当程序到达我打算打印向量的代码部分时,它会执行以下错误: 你不能用cout语句来打印向量吗C++ 如何打印向量?,c++,vector,cout,C++,Vector,Cout,我一直在研究一种将数字输入向量然后输出的方法,但它总是说向量超出范围,并弹出一个非常奇怪的错误。没有任何编译错误,但当程序到达我打算打印向量的代码部分时,它会执行以下错误: 你不能用cout语句来打印向量吗 // Program to ask the user for numbers, and when they are done entering numbers, enter DONE. When DONE, print the vector #include <iostream>
// Program to ask the user for numbers, and when they are done entering numbers, enter DONE. When DONE, print the vector
#include <iostream>
#include <algorithm>
#include <vector>
#define DONE 20
using namespace std;
void l_userinput()
{
int u_Answer;
int vector_Size(0);
int start_Size(0);
vector<int> v_Name(start_Size);
//intialize variables and the initial size of vector
cout << "Please enter numbers and when you are done, type in DONE" << endl;
while (!start_Size)
{
cin >> u_Answer;
vector_Size++;
if (u_Answer == 20)
break;
//Loop until you type in DONE
}
for (int i = 0; i < vector_Size; i++)
{
cout << v_Name[i];
//point of error, Vector out of range?
if (i >= vector_Size)
{
break;
}
}
}
int main()
{
l_userinput();
return 0;
}
您没有将u_答案添加到v_名称,因此当您尝试打印内容时,向量为空。试图访问空向量的任何元素都会导致未定义的行为。您的代码有几个问题。首先,使用附加变量来保持向量大小。这是不需要的-向量有大小成员函数 其次,你根本没有填充你的向量,相反,你只是不断增加你的计数器-因此你试图访问不在向量中的元素 第三,您对DONE的定义与用户键入worddone无关。要完成循环,用户必须输入20。寻求调试帮助的问题此代码为什么不起作用?必须包括所需的行为、特定的问题或错误以及在问题本身中重现这些问题所需的最短代码。请不要发布错误消息的屏幕截图。在问题中包括错误的文本。