2013-05-14 109 views
2

我遇到了问题std::map。 我使用它特定的索引下图对一些列表:std :: map - 如何更改键排序?

map<string, list<pair<string, int> > > List; 

它在Dijkstra算法中使用。 的主要问题是,地图按字母顺序排序string键,这样的:

AAA, AA0, AA1, AAB, AC1 = AA0->AA1->AAA->AAB->AC1 

但我想给它以不同的方式进行排序:

AAA, AA0, AA1, AAB, AC1 = AAA->AAB->AA0->AA1->AC1 

有什么解决办法吗?我读了关于做自己的比较类,但我不知道如何做到这一点。或者也许有其他方法可以解决它?

回答

7

您必须提供您自己的比较函数,在实例化地图时必须将其作为第三个模板参数传递。例如:

struct Comp 
{ 
    bool operator()(const std::string& lhs, const std::string& rhs) const 
    { 
    // implement your comparison logic here 
    } 
}; 

这个类的实例是可调用(因此“函子”)的两个字符串参数,并且基于在一个strict weak ordering逻辑应该返回真或假。

然后实例使用仿函数类型的地图:

std::map<string, list<pair<string, int>>, Comp> List; 

现在的地图将在内部使用的比较逻辑来定义其元素的顺序。

+0

好的,我明白了,但是我怎样才能比较字符串的差异?我的意思是,如何在字符串内找到一个数字? – 2013-05-14 14:10:21

+2

@ user2342783这是一个完全不同的问题。你应该问一个新问题 – stefan 2013-05-14 14:13:12

+0

@ user2342783这是一个不同的问题。但是你可以遍历一个字符串的元素(每个字符都是'char'),并执行诸如call [std :: isdigit](http://en.cppreference.com/w/cpp/string/byte/isdigit)。 – juanchopanza 2013-05-14 14:13:12

-2

是的。您需要提供第三个模板参数,请参阅docs

+5

尽管您的陈述是正确的,但它本身并无帮助。至少要像其他人一样写下一个简单的例子。另外,cplusplus.com不是_the docs_。 – stefan 2013-05-14 14:12:38

2

你必须写你自己的比较器:

struct custom_string_comparer 
{ 
    bool operator()(const std::string& s1, const std::string& s2) 
    { 
     return ...; // your comparison here 
    } 
}; 

map<string, list<pair<string, int>>, custom_string_comparer> List; 
2

像其他人说的,你需要实现一个自定义比较...

struct custom_comparer 
{ 
    bool operator()(const std::string& left, const std::string& right) const 
    { 
     return std::lexicographical_compare(
      left.cbegin(), left.cend(), 
      right.cbegin(), right.cend(), 
      [](char l, char r) -> bool 
      { 
       bool ldigit = isdigit(l) != 0, 
         rdigit = isdigit(r) != 0; 

       return (!ldigit && rdigit) || (ldigit == rdigit && l < r); 
      }); 
    } 
}; 

而且使用它...

std::map<string, list<pair<string, int>>, custom_comparer> List; 

正常string比较运算符使用lexicographical_compare。上面的我的custom_comparer也使用它,但插入了自定义比较器。自定义比较器使用isdigit进行所需的比较。