2012-08-03 106 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