【问题标题】:Compare element of vector of pairs with string c++将对向量的元素与字符串c ++进行比较
【发布时间】: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++


【解决方案1】:

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

进行比较

您可以使用 std::find_if(),而不是重载 operator == 本身,向它传递一个像这样的 lambda:

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

【讨论】:

    猜你喜欢
    • 2013-08-17
    • 1970-01-01
    • 2018-10-04
    • 2021-10-17
    • 1970-01-01
    • 2020-07-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-20
    相关资源
    最近更新 更多