用字符串 c++ 比较对向量的元素
Compare element of vector of pairs with string 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 == 名称(。
如何重载 == 运算符?
这是我得到的错误:
错误 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;
});
相关文章:
- 向量元素的引用地址与它所指向的向量元素的地址不同.为什么
- 在 C++ 中输出枚举类类型的向量元素
- 用向量的向量元素初始化向量的空向量
- 为什么不允许使用可变长度数组作为向量元素?
- 在函数中传递向量元素
- 使用 Rcpp 加速替换迭代算法中的列表和向量元素是否合法?
- 返回向量元素的 l 值的正确方法是什么?
- 当向量增长时,指向向量元素的C++指针是否无效
- 如何在C++中从一个向量元素减去std::unorderede_map向量元素并更新它
- C++:向量元素赋值导致访问冲突
- 将向量元素与字符串元素进行比较,而不初始化向量
- 从2D矢量中找出最小尺寸的向量元素的更好方法
- 当我尝试将一个向量元素的值分配给另一个向量元素时,为什么我的应用程序会崩溃
- 使用递归C++向量元素的总和
- 如何查找为数组中的最低值编制索引的向量元素
- 限制指针访问STL ::向量元素
- 访问索引指向向量元素时的seg故障 - 做错了什么
- 如何使用指针访问向量元素的各个元素
- 向量元素数据损坏了Find()操作
- 将字符值分配给向量元素.C