3

我需要在地图中存储各种字符串,但我想让它们按大小排序。

使用这样的谓词:

struct strsize_less {
    bool operator()(const string& l, const string& r) {
        return l.size() < r.size();
    };
};

将完成排序,但它会丢弃具有相同大小的字符串

int main() {
    typedef map<string, int, strsize_less> mymap_t;
    mymap_t mymap;

    mymap["j"    ] = 0;
    mymap["i"    ] = 1;
    mymap["hh"   ] = 2;
    mymap["gg"   ] = 3;
    mymap["fff"  ] = 4;
    mymap["eee"  ] = 5;
    mymap["dddd" ] = 6;
    mymap["cccc" ] = 7;
    mymap["bbbbb"] = 8;
    mymap["aaaaa"] = 9;

    for( mymap_t::iterator i = mymap.begin(); i!=mymap.end(); ++i )
        cout << "k = " << i->first << " - > v= " << i->second << endl;

    return 0;
}

输出是:

k = j - > v= 1
k = hh - > v= 3
k = fff - > v= 5
k = dddd - > v= 7
k = bbbbb - > v= 9

我的问题:是否有任何谓词可以用来实现以下输出:

k = j - > v= 0
k = i - > v= 1
k = hh - > v= 2
k = gg - > v= 3 
k = fff - > v= 4
k = eee - > v= 5
k = dddd - > v= 6
k = cccc - > v= 7
k = bbbbb - > v= 8
k = aaaaa - > v= 9
4

2 回答 2

14

在比较器中比较大小和字符串:

struct strsize_less
{
    bool operator()(std::string const& l, std::string const& r) const
    {
        if (l.size() < r.size())
            return true;

        if (l.size() > r.size())
            return false;

        return l < r;
    };
};

或者,使用 C++11 的std::tie

struct strsize_less
{
    bool operator()(std::string const& l, std::string const& r) const
    {
        return std::tie(l.size(), l) < std::tie(r.size(), r);
    };
};
于 2012-07-03T17:24:19.673 回答
2
return l.size() < r.size() 
   || (l.size() == r.size() && l < r);
于 2012-07-03T17:27:42.800 回答