Last active
January 1, 2016 22:29
-
-
Save usagi/8209971 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <unordered_map> | |
| #include <map> | |
| #include <vector> | |
| #include <algorithm> | |
| #include <type_traits> | |
| #include <string> | |
| #include <iostream> | |
| int main() | |
| { | |
| using namespace std; | |
| std::unordered_map<std::string, const int> master = | |
| {{ {"ABC", 123} | |
| , {"GHI", 345} | |
| , {"DEF", 123} | |
| , {"XYZ", 234} | |
| , {"UVW", 234} | |
| }}; | |
| std::cout << "=== master data(unordered_map) ===\n"; | |
| for(const auto& p : master) | |
| std::cout << p.first << " : " << p.second << "\n"; | |
| auto sorted_by_key = | |
| std::map<decltype(master)::key_type, decltype(master)::mapped_type> | |
| (std::begin(master), std::end(master)) | |
| ; | |
| std::cout << "=== sort by key ===\n"; | |
| for(const auto& p : sorted_by_key) | |
| std::cout << p.first << " : " << p.second << "\n"; | |
| std::vector | |
| < std::pair | |
| < std::remove_const<decltype(sorted_by_key)::key_type>::type | |
| , std::remove_const<decltype(sorted_by_key)::mapped_type>::type | |
| > | |
| > sorted_by_mapped(std::begin(sorted_by_key), std::end(sorted_by_key)); | |
| std::stable_sort | |
| ( std::begin(sorted_by_mapped), std::end(sorted_by_mapped) | |
| , [](const decltype(sorted_by_mapped)::value_type& a, const decltype(sorted_by_mapped)::value_type& b) | |
| { return a.second < b.second; } | |
| ); | |
| std::cout << "=== sort by mapped (with stable key)\n"; | |
| for(const auto& p : sorted_by_mapped) | |
| std::cout << p.first << " : " << p.second << "\n"; | |
| } |
Author
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
result:
=== master data(unordered_map) ===
UVW : 234
XYZ : 234
DEF : 123
GHI : 345
ABC : 123
=== sort by key ===
ABC : 123
DEF : 123
GHI : 345
UVW : 234
XYZ : 234
=== sort by mapped (with stable key)
ABC : 123
DEF : 123
UVW : 234
XYZ : 234
GHI : 345