我在结构上重载==运算符时遇到问题。
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
andb
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/