I wouldn't choose the different path
inside the sort function. I would use instead different comparators. For instance, have a look at the following code:
#include <list>
#include <string>
#include <iostream>
using namespace std;
struct my_struct
{
my_struct(int i, string s):i(i),s(s){}
int i;
string s;
};
struct CBIA
{
bool operator()(const my_struct & m1, const my_struct & m2){ return m1.i<m2.i; }
};
struct CBID
{
bool operator()(const my_struct & m1, const my_struct & m2){ return m1.i>m2.i; }
};
struct CBSA
{
bool operator()(const my_struct & m1, const my_struct & m2){ return m1.s<m2.s; }
};
struct CBSD
{
bool operator()(const my_struct & m1, const my_struct & m2){ return m1.s>m2.s; }
};
int main()
{
list < my_struct> l;
l.push_back( my_struct(5, string("alpha")));
l.push_back( my_struct(1, string("gamma")));
l.push_back( my_struct(20, string("delta")));
l.push_back( my_struct(-100, string("beta")));
for (;;)
{
int i;
cout << "sort: " << endl << " 0 by int asc" << endl << " 1 by int desc" << endl << " 2 by string asc" << endl << " 3 by string desc" << endl << " -1 quit" << endl;
cin >> i;
if (i == -1) break;
switch(i%4)
{
case 0:
l.sort(CBIA());
break;
case 1:
l.sort(CBID());
break;
case 2:
l.sort(CBSA());
break;
case 3:
l.sort(CBSD());
break;
}
for (list<my_struct>::iterator it = l.begin(); it != l.end(); ++it)
{
cout << "{" << it->i << "," << it->s << "}" << endl;
}
}
}