简体   繁体   English

尝试打印出向量内容时出现编译器错误

[英]Getting compiler error when trying to print out contents of vector

Here's what I have so far: 这是我到目前为止的内容:

 int main(int argc, char const *argv[])
    {
        srand(time(NULL));
        vector<int> deck;
        vector<bool> drawn;
        for (int i = 0; i < 20; i++)
        {
            int numvalue = rand()%20;

            if (drawn[numvalue - 1])  // this checks if their are duplicate values
            {
                i--;
                continue;
            }
            else
            {
                drawn[numvalue - 1] = true;
                //vector<int> deck;
                deck.push_back(numvalue);
            }
        }
        copy (deck.begin(), deck.end(), ostream_iterator<int>(cout, " "));
        return 0;
    }

the Compiler error I'm getting is: 我得到的编译器错误是:

Edit: solved the compiling issue, but now this is seg faulting... 编辑:解决了编译问题,但是现在这是段错误...

I'd like to print out the contents inside my vector deck, and after doing some reading I thought the best option would be to use the function copy. 我想打印出矢量卡座中的内容,经过阅读后,我认为最好的选择是使用函数副本。 Any ideas how I can fix this? 有什么想法我可以解决这个问题吗?

Declare deck at the top of main like such, so it's not declared out of scope 这样在main的顶部声明甲板,因此不会将其声明为超出范围

int main(int argc, char const *argv[])
{
    srand(time(NULL));
    vector<int> deck;
    vector<bool> drawn(20);
    for (int i = 0; i < 20; i++)
    {
        int numvalue = rand()%20;

        if (drawn[numvalue - 1])
        {
            i--;
            continue;
        }
        else
        {
        drawn[numvalue - 1] = true;
        deck.push_back(numvalue);
        }
    }
    copy (deck.begin(), deck.end(), ostream_iterator<int>(cout, " "));
    return 0;
}

Also

int numvalue = rand()%20;

can easily return 0, and with if (drawn[numvalue - 1]), you're accessing drawn[-1] about 5% of the time. 可以轻松返回0,并且如果使用if(drawn [numvalue-1]),则大约有5%的时间访问了drawd [-1]。 Much smarter to change it to: 将其更改为:

int numvalue = rand()%20 +1;

Also as WhozCraig points out below, you never initialized drawn, which will lead to segfaults. 另外,正如WhozCraig在下面指出的那样,您从未初始化绘制,这将导致段错误。

Your deck is being defined in a scope that has finished by the time the copy is called. 您的卡片组在一个范围内定义,该范围在调用副本时已经完成。 Move the declaration of deck up further before the start of the for loop so it remains in scope. 在for循环开始之前,将deck的声明进一步上移,以使其保留在范围内。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM