C ++ std :: map键排序比较功能? [英] C++ std::map key sort comparison function?
问题描述
然而,地图实际上是以最大到最小排序。为什么是这样?当它对地图进行排序时,它不使用键上的比较运算符吗?如何做到这一点?
如果你看std :: map的定义,第三个参数是比较器 - std :: less< Key>
。其默认实现只是调用运算符<
。
您可以尝试在标题中定义新版本其中 YourType
定义如下:
template<>的std ::少< YourType>
{
bool operator()(
const YourType& lhs,
const YourType& rhs)
{
if(!(lhs.member1& rhs.member1))
{
return false;
}
if(!(lhs.member2< rhs.member2))
{
return false;
}
返回true;
}
}
记住朋友 std: :少<
实际测试必须符合以下要求,否则您将收到各种问题:
- lhs< rhs = true
- rha < lhs = false
- lhs< lhs = false
需要注意的一个重要事情(最近我发现的)是,如果你的编译器开始抱怨你重新定义了 std :: less
或其他时髦的东西的含义,可能是您只转发宣布您的 YourType
当你宣布你的 std :: map<您的类型>
。
希望这有帮助!
I have a class where I overload all the comparison operators. I load a bunch of these objects into a map as keys and I expect the map to sort them least to greatest.
However, the map is actually sorted by greatest to least. Why is this? Does it not use the comparison operators on the key when it sorts the map? How can I make it do this?
If you look at the definition for std::map, the 3rd parameter is the comparator - std::less< Key >
by default. The default implementation of which is just to invoke operator<
.
You could try defining a new version in the header where YourType
is defined, like so:
template<> std::less< YourType >
{
bool operator()(
const YourType& lhs,
const YourType& rhs)
{
if(!(lhs.member1 < rhs.member1))
{
return false;
}
if(!(lhs.member2 < rhs.member2))
{
return false;
}
return true;
}
}
Remember to friend std::less< YourType >
in your class.
The actual test must comply with the following or you'll get all kinds of problems:
- lhs < rhs = true
- rha < lhs = false
- lhs < lhs = false
One important thing to note (that I discovered quite recently) is that if your compiler starts complaining that you've redefined the meaning of std::less
or other funky things, it could be that you've only forward declared your YourType
when you declared your std::map< YourType >
.
Hope this helps!
这篇关于C ++ std :: map键排序比较功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!