[英]c++ comparison operators overloading
我在为结构重载 == 运算符时遇到问题。
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
如何使用结构中的两个值而不是第一个值来设置比较元素,就像现在一样?
std::set
使用std::less
作为默认比较器,它使用operator<
进行比较。 并且在您定义的operator<
只提到了数据成员nowString
。 (注意operator==
不用于确定唯一性。)
在标准库使用比较要求的任何地方,唯一性都是通过使用等价关系确定的。 不精确地说,如果两个对象
a
和b
的比较小于另一个,则认为它们是等效的:!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);
}
如何使用结构中的两个值而不是第一个值来设置比较元素
你可以做逻辑或:
bool operator<(const str A, const str B)
{
return ((A.nowString < B.nowString) ||
(A.nowString == B.nowString && A.lastIndex < B.lastIndex));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.