是否可以安全使用操作符=作为运营商的LT!;在一个std ::设置? [英] Is it safe to use operator != as operator < in a std::set?
本文介绍了是否可以安全使用操作符=作为运营商的LT!;在一个std ::设置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一些成员一个结构,我有一个实现运营商==它。是否安全,实现运营商LT;与==操作符的帮助?我想用这个结构在一组,而我要检查这个结构是独一无二的。
I have a struct with some members and I have an implemented operator== for it. Is it safe to implement the operator< with the help of operator==? I want to use this struct in a set, and I want to check that this struct is unique.
struct Data
{
std::string str1;
std::string str2;
std::string str3;
std::string str4;
bool operator==(const Data& rhs)
{
if (str1 == rhs.str1
&& str2 == rhs.str2
&& str3 == rhs.str3
&& str4 == rhs.str4
)
return true;
else
return false;
}
// Is this ok??
bool operator<(const Data& rhs)
{
return !this->operator==(rhs);
}
}
所以,当我插入此结构为std ::设置会发生什么事?
So when I insert this struct to a std::set what will happen?
推荐答案
不,这是相当不安全的。实现它的最简单方法就是通过的std ::领带
。
Nope, it's quite unsafe. The simplest way to implement it is through std::tie
.
#include <tuple>
struct Data
{
std::string str1;
std::string str2;
std::string str3;
std::string str4;
bool operator<(const Data& rhs) const // you forgot a const
{
return
std::tie(str1, str2, str3, str4) <
std::tie(rhs.str1, rhs.str2, rhs.str3, rhs.str4);
}
}
这篇关于是否可以安全使用操作符=作为运营商的LT!;在一个std ::设置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文