用字符串 c++ 比较对向量的元素

Compare element of vector of pairs with string c++

本文关键字:向量 元素 比较 字符串 c++      更新时间:2023-10-16

我有一个名为 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 == 名称(。
如何重载 == 运算符?

这是我得到的错误:

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

实际错误不在x.first == name中,而是在调用std::find(( 中,因为name(即 std::string(将与每个 std::p air<std::string,>

与其重载运算符 == 本身,不如使用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;
});