c++ - 将对向量的元素与字符串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”未定义此运算符或转换为预定义运算符可接受的类型
解决方案
实际错误不在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;
});
推荐阅读
- python - Python Gtk TreeView 列数据显示
- javascript - Gulp 手表不看
- android - 如何向 Android Studio 操作工具栏添加图标?
- ios - 如何在大型导航栏上使用图像作为标题?
- python - Python:为什么函数返回一个字典,其中所有值都由赋值填充?
- java - 使用 java 8 steam 查找两个列表之间的匹配行并映射到另一个对象
- python - 使用 QDesktopService 显示本地 html 文件
- c# - 基于locked bitmap、getpixel和优化辅助函数提高视频校正算法的速度
- matlab - 在没有 fimplicit 或 ezplot 的情况下在 MatLab 中绘制 2 变量隐式函数
- python - Pandas DataFrame - 如何检索 MultiIndex 级别的特定组合