首页 > 解决方案 > 将对向量的元素与字符串c ++进行比较

问题描述

我有一个名为 Champion 的类,其中包含一个成对的向量(字符串和双精度)。将向量的元素与另一个字符串进行比较时遇到问题。

#pragma once
#include <string>
#include<vector>

using namespace std;
class Champion : public Game
{
protected:
    vector<std::pair<string, double> > melee_champ = { { "yasuo",0 }, { "garen",0 }, { "jax",0 }, { "fiora",0 }, { "fizz",0 } };
    vector<std::pair<string, double> > ranged_champ = { {"varus",0 }, {"ezreal",0}, {"lux",0}, {"zoe",0}, {"vayne",0} };
public:
    Champion();
    void write_champ_to_file(string f_name);
    void delete_champ(string type, string name);
};

这是我的课,在实现中我有:

void Champion::delete_champ(string type, string name)
{
    if (type == "melee champ")
    {
        for (pair<string, double>& x : melee_champ)
        {
            if (x.first == name)
            {
                auto itr = std::find(melee_champ.begin(), melee_champ.end(), name);
                melee_champ.erase(itr);
                Champion::write_champ_to_file("temp.txt");
                remove("champ.txt");
                rename("temp.txt", "champ.txt");
            }
        }
    }
}

问题在于比较(x.first == name)。
如何重载 == 运算符?

这是我得到的错误:

错误 C2676 二进制“==”:“std::pair”未定义此运算符或转换为预定义运算符可接受的类型

标签: c++

解决方案


实际错误不在x.first == name但在调用std::find()因为name(即std::string)将与每个std::pair< std::string, double>进行比较

除了重载运算符 == 本身,您还可以通过向std::find_if()传递一个像这样的 lambda 来使用它:

auto itr = std::find_if(melee_champ.begin(), melee_champ.end(), 
    [&name](pair<string, double> const& p) {
        return p.first == name;
    });

推荐阅读