我正在制作纸牌游戏。
在这个游戏中我有球员,他们是球队的成员(每队2名球员),他们可以加入大厅。
所以大厅有一个团队成员,团队都有一名队员。我想直接迭代玩家,而不是每次都经过团队。
相关的C ++代码:
lobby.h
class Lobby {
public:
Lobby(std::string const& name, std::vector<Team> const& teams = std::vector<Team>());
Lobby(){};
~Lobby();
// give cards to all players
void deal();
std::vector<std::shared_ptr<Player> > getPlayers(); // this is the one I'm trying to implement
[...]
private:
std::string _name;
std::vector<Team> _teams;
};
lobby.cpp
[...]
void Lobby::deal()
{
vector<Card> cards = Card::getAllCardsShuffled();
for (int i = 0; i < cards.size(); i++) {
getPlayers()[i % 4].addCard(cards[i]); // this is how I'd like to use getPlayers()
}
cout << _teams[0].getPlayers().at(0).getCards().size() << endl;
// this compiles but I'm not getting any cards in my players (prints 0)
// I think a copy is made somewhere, so I'm always getting new players
}
// this is the method I'm trying to implement...
vector<shared_ptr<Player> > Lobby::getPlayers()
{
return {
make_shared<Player>(_teams[0].getPlayers().at(0)),
make_shared<Player>(_teams[0].getPlayers().at(1)),
make_shared<Player>(_teams[1].getPlayers().at(0)),
make_shared<Player>(_teams[1].getPlayers().at(1))
};
}
[...]
team.h
class Team {
public:
Team();
Team(std::string name);
~Team();
void addPlayer(Player const& player);
void addTrick(Trick const& trick);
void setScore(int const& newScore);
void addPoints(int const& score);
int getScore();
std::vector<Trick> getTricks();
std::vector<Player>& getPlayers();
bool isTeamDealing();
private:
std::string _name;
std::shared_ptr<std::vector<Player> > _players;
int _score;
std::vector<Trick> _wonTricks;
};
team.cpp
Team::Team(string name)
: _name(name)
, _score(0)
, _players(vector<Player>())
{
}
void Team::addPlayer(Player const& player)
{
if (_players.size() < 2) {
_players.push_back(player);
}
}
vector<Player>& Team::getPlayers()
{
return _players;
}
[...]
现在代码可以在团队和玩家之间进行迭代:
void Lobby::deal()
{
vector<Card> cards = Card::getAllCardsShuffled();
for (int i = 0; i < cards.size(); i += 4) {
_teams[0].getPlayers().at(0).addCard(cards[i]);
_teams[0].getPlayers().at(1).addCard(cards[i + 1]);
_teams[1].getPlayers().at(0).addCard(cards[i + 2]);
_teams[1].getPlayers().at(1).addCard(cards[i + 3]);
}
cout << getPlayers().at(0)->getCards().size() << endl;
}
...但我希望能够直接迭代玩家,而不使用2个嵌套循环。有一种简单的方法可以做到这一点吗?
TL; DR 有没有办法实现getPlayers(),允许我迭代一个玩家矢量并直接改变我的玩家?
编辑:我更新了Team中的代码,让Team.getPlayers()返回对向量的引用而不是指针。
答案 0 :(得分:2)
所以我找到了一种方法,使用std::reference_wrapper
:
vector<reference_wrapper<Player> > Lobby::getPlayers()
{
return {
_teams[0].getPlayers().at(0),
_teams[0].getPlayers().at(1),
_teams[1].getPlayers().at(0),
_teams[1].getPlayers().at(1)
};
}
void Lobby::deal()
{
vector<Card> cards = Card::getAllCardsShuffled();
for (int i = 0; i < cards.size(); i++) {
getPlayers().at(i % 4).get().addCard(cards[i]);
}
}
如果有人看到更好的方式,我会尽全力。