4

有谁知道有没有办法可以将地图顺序从更少更改为“更多”?

例如:

有一个map<string, int>test. 我在其中插入了一些条目:

test["b"] = 1;
test["a"] = 3;
test["c"] = 2;

在地图内,顺序为(a, 3)(b, 1)(c, 2)

我希望它是(c, 2)(b, 1)(a, 3)

我怎样才能以简单的方式做到这一点?

4

2 回答 2

10

通过std::greater用作您的密钥而不是std::less.

例如

std::map< std::string, int, std::greater<std::string> > my_map;

请参阅参考资料

于 2012-08-03T00:05:58.493 回答
3

如果您有一个现有的地图,并且您只想反向循环地图的元素,请使用反向迭代器:

// This loop will print (c, 2)(b, 1)(a, 3)

for(map< string, int >::reverse_iterator i = test.rbegin(); i != test.rend(); ++i)
{
    cout << '(' << i->first << ',' << i->second << ')';
}
于 2012-08-03T01:09:18.627 回答