Skip to content

Instantly share code, notes, and snippets.

@usagi
Last active January 1, 2016 22:29
Show Gist options
  • Select an option

  • Save usagi/8209971 to your computer and use it in GitHub Desktop.

Select an option

Save usagi/8209971 to your computer and use it in GitHub Desktop.
#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";
}
@usagi

usagi commented Jan 1, 2014

Copy link
Copy Markdown
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment