Request for improvments

I have written up a class to facilitate sorting of maps and vectors via a sorting map. I have added questions in the forms of comments. Any help would be appreciated.

#include <vector>
#include <algorithm>
#include <map>
#include <string>

#define dic_struc string, int

using namespace std;

template <class T, class U>
class sorting_map
{
private:
map<T, U> s_map; // can this be declaired as a pointer
public: // such that the class would not have to hold the map continence??
sorting_map( map<T, U> s_ ) : s_map(s_) {};
// void operator[](map<T, U> *s_) : s_map(s_) {}; // this would allow the user to change sorting maps on the fly
bool operator()(T x, T y)
{ return s_map[x] < s_map[y]; } // converts x to assigned value and compairs by values
};


int main()
{
vector<int> v;

typedef map<dic_struc> dic_map;
dic_map tmap;
dic_map::iterator ss_it;

tmap["a"] = 5; // make my own sorting sequence
tmap["b"] = 1;
tmap["c"] = 3;
tmap["e"] = 6;
tmap["f"] = 10;
tmap["g"] = 8;

sorting_map<dic_struc> srt(tmap);
//sort(v.begin(), v.end(), srt); // how can this be written current causes many errors

map<string,int,sorting_map<string, int> > mymap3(tmap);
map<dic_struc,sorting_map<dic_struc> > mymap4(tmap);

return 0;
}
This: #define dic_struc string, int is not a good idea.

You are correct to question storing the entire map as a data member of sorting_map. I would use a const reference:

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
#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';
}

demo: http://ideone.com/5uqqC
Thanks for the tips I will incorporate them into future development.
Topic archived. No new replies allowed.