【发布时间】:2023-03-18 15:15:01
【问题描述】:
我有一个名为 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”未定义此运算符或转换为预定义运算符可接受的类型
【问题讨论】:
-
不要从你正在迭代的容器中删除东西。这会把你搞砸的。您收到的错误消息是什么?
-
Error C2676 binary '==': 'std::pair<:string>' 未定义此运算符或转换为预定义运算符可接受的类型
-
您的问题不是
if (x.first == name)行,而是auto itr = std::find(melee_champ.begin(), melee_champ.end(), name);行。您想使用std::find_if并传入一个函数(在您的代码中,lambda 会很好、紧凑和漂亮)这是一个关于主题 stackoverflow.com/questions/12008059/… 的问题 -
没有帮助,因为我需要返回位置以便我可以通过 earse() 删除它,在那个问题中他需要一个布尔返回。
-
std::find_if() 确实返回了一个迭代器。需要在哪里返回 bool?
标签: c++