如何打印出矢量?

时间:2016-06-04 02:12:19

标签: c++ vector cout

我一直在努力将数字输入到矢量然后输出,但它总是说矢量超出范围并弹出一个非常奇怪的错误。没有任何编译错误,但是当程序到达我打算打印出矢量的代码部分时,就会出现这个错误:

Error image

您是否可以使用cout语句打印出矢量?

// 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;
}

2 个答案:

答案 0 :(得分:1)

您未将u_Answer添加到v_Name,因此当您尝试打印内容时,向量为空。尝试访问空向量的任何元素会导致未定义的行为。

答案 1 :(得分:0)

您的代码有几个问题。首先,您使用其他变量来保持矢量大小。这不是必需的 - vector具有size()成员函数。

其次,你根本没有填充你的向量,相反,你只是继续增加你的计数器 - 因此你试图访问不在向量中的元素。

第三,您的#define DONE与用户在单词DONE中输入无关。要完成循环,用户必须输入20。

相关问题