在其他类成员的向量中查找类成员 [英] Finding a classmember in a vector of other class members

查看:112
本文介绍了在其他类成员的向量中查找类成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有类Team和Player。每个团队成员都有一个对象向量播放列表,他的玩家存储在每个玩家现在有一些属性,如ID。现在我想把一个球员转移到一个团队。所以我为此创建了一个函数。

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.

首先我想知道如果玩家b可能已经是团队a的成员,在这种情况下应该打印一条消息。但我没有写一个函数,这样做。

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.

这里是我的尝试(搜索从if循环开始,我想知道球员b是否是球队a的成员)

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;

}



我遇到错误C2678:binary'=='没有操作符发现,它接受类型Player的左手操作数(或没有可接受的转换)。我发现我来自这行

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())

playerlist.end()似乎错了。这部分代码是另一个代码的一些副本,所以我不知道它做什么。我应该放在哪里呢?
5是什么意思?

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 ?

推荐答案

错误给你一个很好的提示:你需要为类 Player 。这是 std :: find 用于确定是否已找到元素。

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.

或者,您可以使用 std :: find_if 使用自定义一元谓词。

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

这篇关于在其他类成员的向量中查找类成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆