繁体   English   中英

收到“向量迭代器不兼容”错误

[英]Receiving the “vector iterators incompatible” error

我正在创建一个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

}

给出错误

我收到的错误信息

编辑

只需在此处发布有关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
}

问题在于get_hand按值返回vector ,因此对get_hand的两次调用创建了不同的向量。 您可以返回对向量的引用,或者只调用一次get_hand

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM