c++ - vector 迭代器+偏移超出范围,在while循环结束时会给出错误

标签 c++ vector

while (deckSize > 2)
{

    one_Card = card_deck.back();
    card_deck.pop_back();

    two_Card = card_deck.back();
    card_deck.pop_back();

    three_Card = card_deck.back();
    card_deck.pop_back();


    oneCard_Name = card_name(one_Card);
    twoCard_Name = card_name(two_Card);
    threeCard_Name = card_name(three_Card);

    oneCard_Suit = card_suit(one_Card);
    twoCard_Suit = card_suit(two_Card);
    threeCard_Suit = card_suit(three_Card);

    oneCard_Rank = card_rank(one_Card);
    twoCard_Rank = card_rank(two_Card);
    threeCard_Rank = card_rank(three_Card);

    bool between1 = (oneCard_Rank < threeCard_Rank && threeCard_Rank < twoCard_Rank);
    bool between2 = (twoCard_Rank < threeCard_Rank && threeCard_Rank < oneCard_Rank);


    cout << "Here are your two cards: " << endl;
    cout << setw(10) << oneCard_Name << " of " << oneCard_Suit << setw(20) << twoCard_Name << " of " << twoCard_Suit << endl;
    cout << "Do you think the next card will lie between these? (y/n): ";
    cin >> user_input;
    cout << endl << endl;
    cout << "Here is your next card: " << endl;
    cout << setw(10) << threeCard_Name << " of " << threeCard_Suit << endl << endl << endl;
    count++;


    if(user_input == "y" || user_input == "yes" || user_input == "Yes" || user_input == "Y")
    {
        if(between1 || between2)
        {
            cout << "You win!" << endl;
            win++;
        }
        else
        {
            cout << "You lose!" << endl;
            lose++;
        }
    }
    else
    {
        if(between1 || between2)
        {
            cout << "You lose!" << endl;

            lose++;
        }
        else
        {
            cout << "You win!" << endl;

            win++;
        }
    }
}


cout << "You have played this game " << count << " times and you have won: " << win << " and lost " << lose << endl;

return 0;


}

这是两个随机播放和初始化平台的子程序

void initDeck(vector<int> &card_deck)
{
    int i;
    for(i = 0; i <= 51; i++)
    {
        card_deck[i] = i;
    }

}


void shuffleDeck(vector<int> & card_deck)
{
    int n;

        for(n = 51; n >= 0; n--)
        {
            int i = randomize();
            int temp = card_deck[i];
            int temp2= card_deck[n];
            card_deck[n] = temp;
            card_deck[i] = temp2;

        }

}


当我运行程序后,它允许我运行它,但是当我达到的数量少于while循环中的条件时,它只会给我一个错误,并且无法完成程序。我之前有此错误并已解决,因此我对错误的含义有基本的了解。据我所知,它正在尝试收集超过向量长度的数字。但是这次我根本看不到我的错误。

最佳答案

deckSize不在任何地方设置/更新。应该是card_deck.size()

关于c++ - vector 迭代器+偏移超出范围,在while循环结束时会给出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22340216/

相关文章:

c++ - 在Vector容器中使用new放置

c++ - 如何用 C++ 编写一个小的内存泄漏检测?

c++ - `std::nullptr_t` 类型的用途是什么?

android - qt 传感器上未定义的引用

c++ - 同一线程上的两个连续 memory_order_release 存储可以相互重新排序吗?

vector - 从离散向量场中提取积分曲线(Mathematica)

c++ - WinApi线程(指针错误)

c++ - Opencv DMatch距离超出范围

c++ - 替代浮点作为关键

c++ - shrink_to_fit 是将容量 a `std::vector` 减小到其大小的正确方法吗?