在push_back()之后删除C ++ Vector项

时间:2015-10-11 14:13:35

标签: c++ vector

我在将对象推送到矢量时遇到问题。

我有三个类:Pack.h,Player.h,Hand.h

Pack处理牌,玩家接受Pack中的牌,然后Hand接受来自玩家的牌。

功能:

打包卡片

bool Pack::Deal(std::vector<Player>players, unsigned int numberOfCards)
{
    //This assumes that if we cannot deal the requested number of cards we do not deal any cards at all.
    //If we wanted to deal as many cards as possibly we would check for errors while iterating over players.

    if (m_pack_of_cards.size() < players.size() * numberOfCards) //check that we have enough cards to complete deal
    {
        std::cout << "Not enough cards to complete deal." << std::endl;
        return false;
    }
    else
    {
        for (unsigned int i = 0; i < numberOfCards; i++)
        {
            for (auto player : players)
            {
                player.Accept_Card_From_Pack(m_pack_of_cards.back());
                m_pack_of_cards.pop_back();
            }
        }
        return true;
    }
}

玩家接受包中的卡

bool Player::Accept_Card_From_Pack(Card card)
{
    m_player_hand.Accept_Card_From_Player(card);
    return true;
}

The Hand接受来自玩家的牌

bool Hand::Accept_Card_From_Player(Card card)
{   
    m_hand_of_cards.push_back(card);
    return true;
}

我的主要功能

int main()
{
    Pack pack = Pack();
    std::vector<Player> players(4);
    for (int i = 0; i < 4; i++)
    {
        players[i] = Player("Player: " + std::to_string(i));
    }

    pack.Deal(players, 8);

    system("pause");
    return 0;
}

这样做是创造一个新的包创建一些玩家,为每个玩家交出一些牌。

玩家拿牌是问题,Pack叫球员接受牌功能,玩家的接受牌功能调用Hand的接受卡功能,然后Hand应该将牌推回到卡牌上。< / p>

它确实将它推回去了,如果我将push_back之前和之后的矢量大小std :: cout从0变为1,它就不会保留该项目,所以下次我推回它时将再次给出0和1作为push_back之前和之后的向量的大小。

哦,这是大学的任务(我必须把它放在这里吗?我不记得了。)

1 个答案:

答案 0 :(得分:3)

想出问题,这通常发生在我发布问题之后,但我会在这里回答,以防有人遇到类似问题。

问题在于玩家交易功能的这一点:

for (auto player : players)
        {
            player.Accept_Card_From_Pack(m_pack_of_cards.back());
            m_pack_of_cards.pop_back();
        }

应该是:

for (auto &player : players)
            {
                player.Accept_Card_From_Pack(m_pack_of_cards.back());
                m_pack_of_cards.pop_back();
            }

如下所述,Eelke和Underscore_d也应该传递参数:

std::vector<Player>players 

as

std::vector<Player>&players