我正在尝试遍历Player对象的向量,然后根据Player指针返回下一个对象。我已经尝试了各种方法来使lambda中的运算符匹配,但无法使其工作并在堆栈溢出时读取类似的此类问题。我很抱歉没有SSCCE,我只是不知道我目前的技能水平。
c_player的来源:
定义为:
Player* current_player;
设置为:
void Game::set_first_player_turn(){
current_player = &game_players.back();
}
错误的代码:
using namespace std;
vector<Player>game_players;
Player* Game::find_player(Player* c_player){
vector<Player>::iterator iter;
iter = find_if(game_players.begin(), game_players.end(),
[&](Player* p ) -> bool{ return p == c_player; }); //This line
// causes the exception. Sets iterator to
// position of the current player
if (iter != game_players.end()){
advance(iter, 1);
}
else{
iter == game_players.begin();
}
current_player = &(*iter);
return current_player;
}
编译错误:
error C2664: 'bool Game::set_game_flow::<lambda_360ac8a355100cfac1adc9f8eba8d8b9>
::operator ()(Player *) const' : cannot convert parameter 1 from 'Player'
to 'Player *'
感谢您的帮助。
答案 0 :(得分:3)
find_if
中的谓词必须对存储在容器中的类型进行const引用。您在向量中存储Player
类型
vector<Player> game_players;
因此
[&](Player* p )
不是正确的谓词。这应该是
[c_player]( const Player& p ) { return p == *c_player; }
// ^^^^^^^^^^^^^^
// to compare by value
// note: to compare by value
// bool operator==( const Player&, const Player&)
// must be defined
[c_player]( const Player& p ) { return &p == c_player; }
// ^^^^^^^^^^^^^^
// to compare by address
// note: address of c_player
// has to be valid (not invalidated by vector through resizing, erasing, etc)
所以你可以写:
vector<Player>::iterator iter;
iter = find_if( game_players.begin(), game_players.end(),
[c_player]( const Player& p ) { return p == *c_player;});