少于操作员并不能保证对对象集的独特性
我正在尝试构建一组称为 guest 的对象。为此,我重载了小于运算符。问题是我没有得到独特的元素。我不明白为什么。在以下示例中,集合的大小始终为 2。
// Online C++ compiler to run C++ program online
#include <iostream>
#include <set>
#include <string>
class Guest{
public:
Guest(const std::string &fn, const std::string &ln, const std::string &em, const std::string &loy):firstname(fn), lastname(ln), email(em),loyalty(loy){}
std::string firstname;
std::string lastname;
std::string email;
std::string loyalty;
};
bool operator<(const Guest& l, const Guest& r){
return (l.firstname < r.firstname) or ((l.firstname == r.firstname) and
((l.lastname < r.lastname) or ((l.lastname == r.lastname) and
((l.email < r.email) or ((l.email == r.email) and
((l.loyalty < r.loyalty) or ((l.loyalty == r.loyalty))))))));
}
int main() {
Guest g1("g1","g2","g3","g4");
Guest g2("g1","g2","g3","g4");
std::set<Guest> guests = {g1,g2};
std::cout << guests.size() << std::endl; //Size is always 2 in here. It should be 1
return 0;
}
I am trying to construct a set of objects called guests. For this purpose, I overloaded the less than operator. The problem is that I'm not getting unique elements. I can't figure out why. The size of the set is always 2 in the following example.
// Online C++ compiler to run C++ program online
#include <iostream>
#include <set>
#include <string>
class Guest{
public:
Guest(const std::string &fn, const std::string &ln, const std::string &em, const std::string &loy):firstname(fn), lastname(ln), email(em),loyalty(loy){}
std::string firstname;
std::string lastname;
std::string email;
std::string loyalty;
};
bool operator<(const Guest& l, const Guest& r){
return (l.firstname < r.firstname) or ((l.firstname == r.firstname) and
((l.lastname < r.lastname) or ((l.lastname == r.lastname) and
((l.email < r.email) or ((l.email == r.email) and
((l.loyalty < r.loyalty) or ((l.loyalty == r.loyalty))))))));
}
int main() {
Guest g1("g1","g2","g3","g4");
Guest g2("g1","g2","g3","g4");
std::set<Guest> guests = {g1,g2};
std::cout << guests.size() << std::endl; //Size is always 2 in here. It should be 1
return 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您应该删除最后一部分
或(((l.loyalty == r.loyalty)))
,否则操作员&lt;
将返回true
guest
的数据成员是等效的。或使用
std :: TIE
使其变得更简单。You should remove the last part
or ((l.loyalty == r.loyalty))
, otherwise theoperator<
would returntrue
when all the data members ofGuest
are equivalent.Or make it much simpler with
std::tie
.