简体   繁体   中英

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

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. 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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