我在结构上重载==运算符时遇到问题。
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
如何使用结构中的两个值而不是现在看来的第一个值来使集合比较元素?
答案 0 :(得分:4)
std::set
使用std::less
作为默认比较器,它使用operator<
进行比较。并且在您定义的operator<
中仅提及数据成员nowString
。 (请注意,operator==
并不用于确定唯一性。)
在标准库使用Compare要求的所有地方,唯一性都是通过使用等价关系确定的。用不精确的术语来说,如果两个对象
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);
}
答案 1 :(得分:1)
如何使用结构中的两个值而不是第一个值来设置比较元素
您可以进行逻辑或:
bool operator<(const str A, const str B)
{
return ((A.nowString < B.nowString) ||
(A.nowString == B.nowString && A.lastIndex < B.lastIndex));
}