std :: map - 如何更改键排序? [英] std::map - how to change key sorting?
问题描述
我有一个问题与 std :: map
。
我使用它来映射在特定索引下的一些对的列表:
I have a problem with std::map
.
I'm using it to map some list of pairs under a specific index:
map<string, list<pair<string, int> > > List;
它用于Dijkstra算法。
主要的问题是map按字母顺序排序 string
键,例如:
It's used in Dijkstra algorithm.
The main problem is that map sorts string
keys in alphabetical order, like this:
AAA, AA0, AA1, AAB, AC1 = AA0->AA1->AAA->AAB->AC1
但我想用不同的方式排序:
But I would like to sort it in a different way:
AAA, AA0, AA1, AAB, AC1 = AAA->AAB->AA0->AA1->AC1
有没有任何解决方案?我读了关于做自己的比较课,但我不知道如何做到这一点。
Is there any solution to this? I read about making my own comparing class, but I have no idea how to do this. Or maybe there's some other way to solve it?
推荐答案
你必须提供自己的比较函子,它必须作为3rd实例化地图时的模板参数。例如:
You have to provide your own comparison functor, which must be passed as 3rd template parameter when instantiating the map. For example:
struct Comp
{
bool operator()(const std::string& lhs, const std::string& rhs) const
{
// implement your comparison logic here
}
};
这个类的实例是可调用的(因此是functor),有两个字符串参数,或基于严格弱排序逻辑的错误。
Instances of this class is callable (hence "functor") with two string parameters, and should return true or false based in a strict weak ordering logic.
然后使用函子类型实例化地图:
Then instantiate the map using the functor type:
std::map<string, list<pair<string, int>>, Comp> List;
现在地图将在内部使用您的比较逻辑来定义其元素的排序。
Now the map will use your comparison logic internally to define the ordering of its elements.
这篇关于std :: map - 如何更改键排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!