接收"矢量迭代器不兼容"错误

时间:2014-04-28 02:29:15

标签: c++ pointers object vector reference

我正在创建一个Uno游戏,我试图通过特定属性搜索对象向量。当程序到达Game :: player_selection()方法时崩溃。除此之外,一切正常。

#include <vector>
#include <iostream>
#include <algorithm>

using namespace std;

class Card {
public:
  string get_colour();
  string get_type();
};

class Player {
public:
  vector<Card*> get_hand(); //Should this be a reference?
private:
  vector<Card*>current_cards;
};


int main() {
srand(time(NULL)); //Makes shuffle more random (different every time)
Game my_game;
Player new_player("Hank", "human");
Player jack_player("Jack", "human");
my_game.add_player(new_player); //Must create players before doing other tasks
my_game.add_player(jack_player); //Must create players before doing other tasks
my_game.setup_game();
my_game.display_players();

cout << "enter colour" << endl;
cin >> colour;
cout << "enter type" << endl;
cin >> type;

my_game.play_card_to_pile(my_game.player_selection("Jack", colour, type));
my_game.display_players();

Game.cpp

Card* Game::player_selection(string p_name, string colour, string type){
    vector<Player>::iterator p_iter;
    vector<Card*>::iterator c_iter;
    p_iter = find_if (game_players.begin(), game_players.end(), [&] (Player& p) -> bool{return p.get_name() == p_name;}); //Finds correct player
    c_iter = find_if(p_iter->get_hand().begin(), p_iter->get_hand().end(), [&] (Card*& c) -> bool{return c->get_colour() == colour && c->get_type() == type;}); //Finds correct card

    return (*c_iter);//Should return correct card

}

错误

Error message I receive

修改

仅发布此处以供将来参考有关find_if检查和向量的多个副本。所以解决方案是:

Card* Game::player_selection(string p_name, string colour, string type){
    vector<Player>::iterator p_iter;
    vector<Card*>::iterator c_iter;
    p_iter = find_if (game_players.begin(), game_players.end(), [&] (Player& p) -> bool{return p.get_name() == p_name;});
    if (p_iter != game_players.end()){
        vector<Card*> hand = p_iter->get_hand();//Otherwise have multiple copies of the vector stored in different places in memory
        c_iter = find_if(hand.begin(), hand.end(), [&] (Card*& c) -> bool{return c->get_colour() == colour && c->get_type() == type;});
        if (c_iter != hand.end()){
            return (*c_iter); //If found return found Card
        }
    }
    return (get_pile_card()); //Else return a default
}

1 个答案:

答案 0 :(得分:1)

问题是get_hand按值返回vector,因此对get_hand的2次调用会创建不同的向量。您可以返回对向量的引用,或只调用get_hand一次:

vector<Card*> hand = p_iter->get_hand();
c_iter = find_if(hand.begin(), hand.end(), ...

您还应检查对find_if的两次调用的结果,以确保他们确实找到了满足谓词的项目。

相关问题