#include <iostream>
#include <algorithm>
#include <vector>
#include <tuple>
using namespace std;
struct Army
{
private:
int numberSuffix;
int armyCode;
protected:
string name;
public:
Army (int armycode, int suffix):armyCode (armycode),
numberSuffix (suffix), name ("Shirley") {}
int getArmyCode () const
{
return armyCode;
}
int getNumberSuffix () const
{
return numberSuffix;
}
//Method 1: of sorting default comparator function
bool operator< (const Army & other)
{
cout << " Using default Operator< as comparator " << endl;
//return (getArmyCode() < other.getArmyCode());
/* This would first check if the armyCode is less
* then secondly would check numberSuffix, and later
* the name. */
return std::tie (armyCode, numberSuffix, name)
< std::tie (other.armyCode, other.numberSuffix, other.name);
}
};
//Method 2: of Sorting comparator function
bool
sortArmy (const Army & lhs, const Army & rhs)
{
cout << " Using function as Comparator " << endl;
return (lhs.getArmyCode () < rhs.getArmyCode ());
//return std::tie(lhs.getArmyCode(), lhs.getNumberSuffix(), lhs.name)
// < std::tie(rhs.getArmyCode(), rhs.getNumberSuffix(), rhs.name);
}
int
main ()
{
vector < Army > listOfArmy;
Army a1(25, 11);
//cout << "The officer's Name is " << a1->getArmyCode () << endl << endl;
Army a2(23, 1);
//cout << "The 2nd officer's Name is " << a2->getArmyCode () << endl << endl;
listOfArmy.push_back (a1);
listOfArmy.push_back (a2);
vector < Army >::iterator it;
cout << "Class Entities stored as vector: " << endl;
for (it = listOfArmy.begin (); it != listOfArmy.end (); ++it)
{
cout << it->getArmyCode () << " " << it->getNumberSuffix () << endl;
}
cout << "After sorting the vectors: " << endl;
// sort(listOfArmy.begin(), listOfArmy.end()); // Method 1: Default operator<
//sort(listOfArmy.begin(), listOfArmy.end(), sortArmy); // Method 2: Using comparator function
sort (listOfArmy.begin (), listOfArmy.end (),
[](const Army & lhs, const Army & rhs)
{
return (lhs.getArmyCode () < rhs.getArmyCode ());
}); // Method 3: LAMBDA expression
for (it = listOfArmy.begin (); it != listOfArmy.end (); ++it)
{
cout << it->getArmyCode () << " " << it->getNumberSuffix () << endl;
}
return 0;
}