/** * * @file LessThanAbstrGen.cpp * * @authors M. Laporte, D. Mathieu * * @date 07/12/2011 * * @version V1.0 * **/ #include <string> #include <vector> #include <iostream> using namespace std; namespace { template <typename T> class ILessThanGen { public : virtual ~ILessThanGen (void) {} virtual bool operator () (const T &, const T &) const = 0; }; // ILessThanGen class Pers { string myNom; unsigned myAge; public : Pers (const string & nom, unsigned age) : myNom (nom), myAge (age) {} const string & getNom (void) const noexcept { return myNom; } unsigned getAge (void) const noexcept { return myAge; } private : ostream & display (ostream & os) const { return os << getAge() << " - " << getNom(); } // display() public : friend ostream & operator << (ostream & os, const Pers & p) { return p.display (os); } }; // Pers class TriParAgeAsc : public ILessThanGen <Pers> { public : virtual ~TriParAgeAsc (void) noexcept {} virtual bool operator () (const Pers & p1, const Pers & p2) const noexcept { return p1.getAge () <= p2.getAge (); } // operator () }; // TriParAgeAsc class TriParNomDesc : public ILessThanGen <Pers> { public : virtual ~TriParNomDesc (void) noexcept {} virtual bool operator () (const Pers & p1, const Pers & p2) const noexcept { return p1.getNom () >= p2.getNom (); } // operator () }; // TriParNomDesc template <typename Iter_t, class LessThan> void selectSort (Iter_t deb, Iter_t fin, const LessThan & isInf) { if (fin <= deb) return; for ( ; deb < fin - 1; ++deb) { Iter_t rgMin = deb; for (Iter_t j (deb + 1); j < fin; ++j) if (isInf (*j, *rgMin)) rgMin = j; swap (*deb, *rgMin); } } // selectSort() void lessThanAbstrGen (void) { cout << "LessThanAbstrGen : \n"; typedef vector <Pers> CVPers; CVPers vPers; vPers.push_back ( Pers ("Charlotte", 21)); vPers.push_back ( Pers ("Alfred", 12)); vPers.push_back ( Pers ("Jean", 42)); vPers.push_back ( Pers ("Noemie", 11)); vPers.push_back ( Pers ("Berthe", 99)); vPers.push_back ( Pers ("Agathe", 29)); vPers.push_back ( Pers ("Sylvain", 42)); vPers.push_back ( Pers ("Pierre", 75)); cout << "Tri par age croissant\n\n"; selectSort (vPers.begin (), vPers.end (), TriParAgeAsc ()); for (const Pers & personne : vPers) cout << personne << '\n'; cout << "Tri par nom decroissant\n\n"; selectSort (vPers.begin (), vPers.end (), TriParNomDesc ()); for (const Pers & personne : vPers) cout << personne << '\n'; } // lessThanAbstrGen() } // namespace int main (void) { lessThanAbstrGen (); return 0; } // main()