Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
539 views
in Technique[技术] by (71.8m points)

c++ - Finding a classmember in a vector of other class members

I have the classes Team and Player. Every Team member has an object vector playerlist with his players stored in. Every player now has some attributes like ID. Now i want to transfer a Player to a Team . So i created a function for this.

First i want to findout if the Player b maybe is already a member of Team a, in which case a message should be printed out. But i failed in writing a function which does this.

Here is my try(the search starts in the if loop, where i want to find out if Player b is member of Team a)

#include <vector>
#include <string>
#include <iostream>

using namespace std;

class Player
{
public:

private:


};

class Team
{
public:


    vector<Player> getplayerlist(){
        return playerlist;
    }
    string getteamname(){
        return teamname;
    }
    void playerbuy(Team a, Player b)
    {
        vector<Player> playerlist;
        playerlist = a.getplayerlist();
        if (find(playerlist.begin(), playerlist.end(), 5) != playerlist.end()) {

        }
        else {
            cout << "This player is not member of " << a.getteamname();
        }
    }

private:
    vector<Player> playerlist;
    string teamname;
};

int main()
{
    return 0;

}

I got the error C2678: binary '==' : no operator found which takes a left-hand operand of type 'Player' (or there is no acceptable conversion). I figured out i comes from the line

if (find(playerlist.begin(), playerlist.end(), 5) != playerlist.end())

The =! playerlist.end() seems to be wrong there. This part of the code is some copy of another code so i don't know what it does. What should i put in there instead ? And what does the 5 means ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The error is giving you a good hint: you need to implement an equality operator for class Player. That is what std::find uses to determine if an element has been found.

Alternatively, you can use std::find_if with a custom unary predicate.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...