Andrey Asked:2020-06-26 03:50:17 +0000 UTC2020-06-26 03:50:17 +0000 UTC 2020-06-26 03:50:17 +0000 UTC 如何按值对 std::map 进行排序? 772 吃饭吧 std::map<string, int> MyMap; 如何从最大值开始显示容器的内容? 容器本身不再使用。 c++ 3 个回答 Voted Best Answer gil9red 2020-06-26T05:14:50Z2020-06-26T05:14:50Z 例如: map<string, int> MyMap; MyMap["3"] = 30; MyMap["1"] = 10; MyMap["2"] = 20; MyMap["4"] = 0; for (pair<string, int> pair : MyMap) { cout << pair.first << ": " << pair.second << '\n'; } cout << '\n'; map<int, string> reverseMyMap; for (pair<string, int> pair : MyMap) { reverseMyMap[pair.second] = pair.first; } cout << "Reverse:\n"; map<int, string>::reverse_iterator it = reverseMyMap.rbegin(); while (it != reverseMyMap.rend()) { cout << it->first << ": " << it->second << '\n'; it++; } 安慰: 1: 10 2: 20 3: 30 4: 0 Reverse: 30: 3 20: 2 10: 1 0: 4 Harry 2020-06-26T03:55:10Z2020-06-26T03:55:10Z 执行迭代不是从.begin()到.end(),而是从 .rbegin()到.rend()- 简而言之,使用reverse_iterator. Dev Null 2020-08-09T13:33:48Z2020-08-09T13:33:48Z 如果求助次数足够多,最好使用boost::multi_index_containerfrom ordered_uniquetostd::string和ordered_non_uniqueto int。
例如:
安慰:
执行迭代不是从
.begin()
到.end()
,而是从.rbegin()
到.rend()
- 简而言之,使用reverse_iterator
.如果求助次数足够多,最好使用
boost::multi_index_container
fromordered_unique
tostd::string
和ordered_non_unique
toint
。