C++ 实施运营商<;在C++;
我有一个带有几个数字字段的类,例如:C++ 实施运营商<;在C++;,c++,operators,operator-overloading,operator-keyword,C++,Operators,Operator Overloading,Operator Keyword,我有一个带有几个数字字段的类,例如: class Class1 { int a; int b; int c; public: // constructor and so on... bool operator<(const Class1& other) const; }; 这篇文章背后的全部原因就是我发现上面的实现太冗长了。应该有更简单的方法。我假设您想要实现字典排序 在C++11之前: #include <boost/tuple/t
class Class1 {
int a;
int b;
int c;
public:
// constructor and so on...
bool operator<(const Class1& other) const;
};
这篇文章背后的全部原因就是我发现上面的实现太冗长了。应该有更简单的方法。我假设您想要实现字典排序 在C++11之前:
#include <boost/tuple/tuple.hpp>
#include <boost/tuple/tuple_comparison.hpp>
bool Class1::operator<(const Class1& other) const
{
return boost::tie(a, b, c) < boost::tie(other.a, other.b, other.c);
}
#包括
#包括
bool Class1::operator您可以执行以下操作:
return memcmp (this, &other, sizeof *this) < 0;
returnmemcmp(this,&other,sizeof*this)<0;
但这有很多警告——例如没有vtbl,我肯定还有很多。这取决于订购对您是否重要。如果没有,您可以这样做:
bool operator<(const Class1& other) const
{
if(a == other.a)
{
if(b == other.b)
{
return c < other.c;
}
else
{
return b < other.b;
}
}
else
{
return a < other.a;
}
}
bool操作符我认为对map
的要求存在误解
map
不要求类具有operator避免多次缩进的版本
bool operator<(const Class1& other) const
{
if(a != other.a)
{
return a < other.a;
}
if(b != other.b)
{
return b < other.b;
}
return c < other.c;
}
bool operator您必须首先决定什么是“谢谢”!!这就是我要找的。或者,为了好玩,返回一个=other.a?我不知道这在什么方面比OP给出的“简单化实现”更好。这个版本不太可读。很好!但是boost对于我的特殊情况来说太重了。太好了,从来没有想过使用元组@阿格内尔·库里安:除了这条领带,没必要再“使用”它了。它也是头文件,为了最小化生成影响(时间/依赖关系),可以将它隔离成单独的编译单元(但对于发布版本,请考虑在内联的标题中执行它)。使用最新的编译器,您可以在包含header:)之后使用std::tie@Peter:OP只希望保证唯一性,只要任何字段不相等
,因此,添加偏移量以获取第一个键字段的地址并确保键字段是连续的,memcmp应该可以做到这一点。
bool operator<(const Class1& other) const
{
if(a == other.a)
{
if(b == other.b)
{
return c < other.c;
}
else
{
return b < other.b;
}
}
else
{
return a < other.a;
}
}
struct Compare: std::binary_function<Key,Key,bool>
{
bool operator()(const Key& lhs, const Key& rhs) const { ... }
};
typedef std::map<Key,Value,Compare> my_map_t;
bool operator<(const Class1& other) const
{
if(a != other.a)
{
return a < other.a;
}
if(b != other.b)
{
return b < other.b;
}
return c < other.c;
}