std :: map - 如何更改键排序? [英] std::map - how to change key sorting?

查看:172
本文介绍了std :: map - 如何更改键排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个问题, 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算法。
主要问题是地图按字母顺序排序 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?

推荐答案

你必须提供自己的比较函子,必须通过第3实例化地图时的模板参数。例如:

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)具有两个字符串参数,并且应该返回true或者基于严格弱订购逻辑的错误。

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆