c++ - C++比较运算符重载

标签 c++ operator-overloading structure

我在结构上重载==运算符时遇到问题。

struct str
{
    string nowString;
    int lastIndex;
};
bool operator < (const str A, const str B)
{
    return(A.nowString < B.nowString);
}
bool operator == (const str A, const str B)
{
    if (A.nowString == B.nowString && A.lastIndex == B.lastIndex)
        return(true);
    else
        return(false);
}
我有
    set <str> A;
    A.insert({"a", 1});
    A.insert({"a", 1});
    A.insert({"a", 2});
    A.insert({"b", 1});
    for (auto t = A.begin(); t != A.end(); t++)
    {
        cout << (*t).nowString << " " << (*t).lastIndex << endl;
    }
我得到
a 1
b 1
作为输出,但我想得到
a 1
a 2
b 1
如何使用结构中的两个值而不是第一个值来设置set比较元素?

最佳答案

std::set 使用std::less作为默认比较器,该比较器使用operator<进行比较。在您定义的operator<中,仅提及数据成员nowString。 (请注意,operator==不用于确定唯一性。)

Everywhere the standard library uses the Compare requirements, uniqueness is determined by using the equivalence relation. In imprecise terms, two objects a and b are considered equivalent if neither compares less than the other: !comp(a, b) && !comp(b, a).


您可以将operator<更改为
bool operator < (const str& A, const str& B)
{
    return std::tie(A.nowString, A.lastIndex) < std::tie(B.nowString, B.lastIndex);
}

关于c++ - C++比较运算符重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63764308/

相关文章:

c - 在 C 中使用指针循环遍历结构元素

c# - 每层的 MVVM 角色

c++ - 将模板化的 std::array<std::vector<T>, N> 放入构造函数初始化列表中

c++ - 当它应该是字符串时输入接受字符?

delphi - Delphi 支持哪些类型的运算符重载?

javascript - 如何在 TypeScript 中进行方法重载?

C++ Ubuntu。使用 FFMPEG 库编译的多个 undefined reference

C++ 宏 - 大写字符串

c++ - 我可以专门化运算符<<吗?

mysql - 如何破译这个mysql数据的结构?