【问题标题】:dealing at the same time with list and vector of object同时处理对象的列表和向量
【发布时间】:2021-09-04 10:36:12
【问题描述】:

我必须创建一个迷你扑克游戏。我创建了两个类CardHand

我尝试使用 for_each 循环向每个玩家发一张牌,但编译器写道 push_back 与参数列表不匹配。我尝试了不同的选择,但没有成功。我该如何解决这个问题?

此外,我必须编写一个函数来判断玩家何时有同花,以便有超过 5 张具有相同花色的牌,包括已经在桌面上的花色。一张牌桌由“手锅”表示。对于这件事,我必须使用suits vector。我不知道如何开始做这个功能。

你能解释一下为了实现这样的功能我必须做的步骤吗?

enum Suit
{
    SPADES = 0, HEARTS, CLUBS, DIAMONDS
};
class Card //Card
{
public:
    int number;
    Suit suit;
};
class Hand //One person
{
public:
    vector<Card> cards;
    int money;
};

vector<Card> Join(Hand a, Hand b)
{
    vector<Card> ab;
    for (auto it = a.cards.begin(); it < a.cards.end(); it++)
        ab.push_back(*it);
    for (auto it = b.cards.begin(); it < b.cards.end(); it++)
        ab.push_back(*it);
    return ab;
}
int main()
{
    stack<Card> deck;
    list<Hand> players;
    Hand pot;
    for (auto it = players.begin(); it != players.end(); it++)
    {
        players.push_back((*it).cards.push_back(deck.pop()));  //This line cause that I can't compile code
    }

    vector<Suit> suits = { SPADES, HEARTS, CLUBS, DIAMONDS };
    //Here I have to write code that display which player has a flush
}

【问题讨论】:

  • @SamVarshavchik 我已经在列表中使用了 push_back 和 push_front,并且可以正常工作。所以我认为这不是问题
  • 您正在调用(*it).cards.push_back(deck.pop()),然后尝试获取此调用的返回值并将其传递给players.push_back。但是第一次调用不会返回任何结果:push_back 被声明为返回void。所以这条线没有任何意义。
  • 此外,players 列表为空。如果并且当您编译此代码时,该循环将不会运行,也不会做任何事情。

标签: c++ list class vector


【解决方案1】:

要修复您看到的编译器错误,请尝试以下操作:

    for (auto it = players.begin(); it != players.end(); it++)
    {
        // use deck.top() here instead of deck.pop()
        it->cards.push_back(deck.top());
        
        // then pop after you've push_back'd
        deck.pop();
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-07-01
    • 1970-01-01
    • 2014-06-26
    • 2020-04-06
    • 2012-02-21
    • 1970-01-01
    • 2018-05-25
    • 2012-10-23
    相关资源
    最近更新 更多