w kontekscie sortowania po roznych polach, wierz mi, chodzi o zastosowanie szablonu -- funkcji sortujacej:
#include <iostream>
#include <list>
struct element
{ bool flaga;
std::string napis;
int liczba;
element(bool f, std::string const& n, int l):flaga(f),napis(n),liczba(l){}
};
void wypisz(std::list<element> const & t)
{ using namespace std;
list<element>::const_iterator it=t.begin(), end=t.end();
while(it!=end)
{ cout << "F= " << it->flaga << " N='" << it->napis << "' L=" << it->liczba << endl;
++it;
}
}
//sortowanie przez wstawianie, z pomoca listy pomocniczej, zeby bylo latwo przesledzic co sie dzieje
template<typename T>
void sort(std::list<element> & t, T element::* wskaznik)
{
if(t.size() < 2) return;
std::list<element> out;
std::list<element>::iterator it, it_out;
while(!t.empty())
{
it = t.begin();
it_out = out.begin();
while( it_out != out.end() )
if( (*it).*wskaznik > (*it_out).*wskaznik ) //nie wazne na jaki typ "T" pokazuje wskaznik
++it_out; //wazne jedynie aby ten typ mial swoj operator >
else
break;
//*przeniesienie* elementu IT z listy T, do listy OUT na pozycje IT_OUT
out.splice(it_out, t, it);
}
//*przeniesienie* wszystkich elementow z OUT do T
t.splice(t.end(), out);
}
int main()
{ using namespace std;
list<element> tab;
tab.push_back(element(false, "A", 4));
tab.push_back(element(false, "D", 3));
tab.push_back(element(true, "B", 2));
tab.push_back(element(true, "C", 1));
cout << "Po fladze: " << endl;
sort(tab, &element::flaga);
wypisz(tab);
cout << endl;
cout << "Po napisie: " << endl;
sort(tab, &element::napis);
wypisz(tab);
cout << endl;
cout << "Po liczbie: " << endl;
sort(tab, &element::liczba);
wypisz(tab);
cout << endl;
}
-sh-3.00# g++ -Wall -ansi -pedantic x.cpp
-sh-3.00# ./a.out
Po fladze:
F= 0 N='D' L=3
F= 0 N='A' L=4
F= 1 N='C' L=1
F= 1 N='B' L=2
Po napisie:
F= 0 N='A' L=4
F= 1 N='B' L=2
F= 1 N='C' L=1
F= 0 N='D' L=3
Po liczbie:
F= 1 N='C' L=1
F= 1 N='B' L=2
F= 0 N='D' L=3
F= 0 N='A' L=4