2012-08-03 109 views
4

有谁知道有没有一种方法可以将地图顺序从少量更改为“更多”?如何更改要反转的std :: map的顺序?

例如:

有一个名为testmap<string, int>。我插入一些条目到它:

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

里面的地图,订货会(a, 3)(b, 1)(c, 2)

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

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

回答

9

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

例如

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

the reference

+0

太谢谢你了为你的答案。这正是我所需要的。我以前看过一次。我现在回想起这个用法。欣赏。 @GManNickG也欢迎:) – 2012-08-03 00:55:28

+0

@XinLi欢迎来到SO。请查看[faq](http://stackoverflow.com/faq),了解网站的工作原理并理解upvoting和接受答案。玩的很开心。 – pmr 2012-08-03 07:58:13

+0

谢谢。我会看看。 – 2012-08-08 19:34:15

2

如果您有现成的地图,只是想和你遍历反向映射的元素,用一个反向迭代:

// 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 << ')'; 
} 
+0

嗨@beerboy,你给了我另一种思考我的编码的方式。谢谢。 – 2012-08-08 19:35:53