language: C++11 (gcc-4.7.2)
date: 527 days 4 hours ago
link:
visibility: public
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include <vector>
#include <algorithm>
#include <map>
#include <string>
#include <iostream>
#include <iterator>
 
template <class T, class U>
class sorting_map 
{ 
    const std::map<T, U>& s_map;
 public:
    sorting_map(const std::map<T, U>& s_ ) : s_map(s_) {}
    bool operator()(T x, T y) const { return s_map.at(x) < s_map.at(y); }
};
 
using namespace std;
int main()
{
    map<string, int> tmap = {{"a", 5}, {"b", 1}, {"c", 3}, {"e", 6}, {"f", 10}, {"g", 8}};
 
    vector<string> v = {"a", "b", "c", "f", "g"}; 
 
    cout << "Before sorting: ";
    copy(v.begin(), v.end(), ostream_iterator<string>(cout, " "));
    cout << '\n';
 
    sort(v.begin(), v.end(), sorting_map<string, int>(tmap));
 
    cout << "After sorting: ";
    copy(v.begin(), v.end(), ostream_iterator<string>(cout, " "));
    cout << '\n';
 
    map<string, int, sorting_map<string, int> > mymap3(tmap); 
    mymap3["a"] = 100;
    mymap3["b"] = 200;
    mymap3["c"] = 300;
    for(auto i = mymap3.begin(); i!=mymap3.end(); ++i)
        std::cout << "mymap3[" << i->first << "] = " << i->second << '\n';
}