Code:
#include <string>
#include <vector>
#include <set>
#include <algorithm>
#include <iterator>
#include <iomanip>
struct person
{
std::string firstname;
std::string lastname;
int age;
person(const std::string& fname,
const std::string& lname,
int yrs) : firstname(fname), lastname(lname), age(yrs)
{
// Empty constructor
}
};
//Overloaded operator<<
std::ostream& operator<<(std::ostream& lhs, const person& rhs)
{
return lhs << "Name: " << std::setw(10) << std::left << rhs.lastname
<< ", " << std::setw(12) << std::left << rhs.firstname
<< "\tAge: " << rhs.age;
}
// Default sort method: sorts according to lastname, firstname
struct default_sort
{
inline bool operator()(const person& lhs, const person& rhs) const
{
if( lhs.lastname == rhs.lastname )
{
return lhs.firstname < rhs.firstname;
}
else
return lhs.lastname < rhs.lastname;
}
};
// Sort by age, then lastname
struct age_sort
{
inline bool operator()(const person& lhs, const person& rhs) const
{
if(lhs.age == rhs.age)
{
return lhs.lastname < rhs.lastname;
}
else
return lhs.age < rhs.age;
}
};
// SET container uses the less-than operator as a default for how to sort
bool operator<(const person& lhs, const person& rhs)
{
return default_sort()(lhs,rhs);
}
int main()
{
std::set<person> personSet;
std::vector<person> personVect;
person people[] = {person("Bart","Simpson",12),
person("Lisa","Simpson",10),
person("Marge","Simpson",38),
person("Homer","Simpson",40),
person("Montgomery","Burns",100),
person("Milhouse","Van Houten",12)};
const int num_people = sizeof(people)/sizeof(person);
// Load set/vector with data from the array
std::copy(people,people+num_people,back_inserter(personVect));
std::copy(people,people+num_people,inserter(personSet,personSet.end()));
// Display set contents, container is automatically sorted according to operator<
std::cout << "Writing contents of SET container: " << std::endl;
std::copy(personSet.begin(),personSet.end(),
std::ostream_iterator<person>(std::cout,"\n"));
// Display vector contents, unsorted currently
std::cout << "\n\nWriting contents of VECTOR container (unsorted): " << std::endl;
std::copy(personVect.begin(),personVect.end(),
std::ostream_iterator<person>(std::cout,"\n"));
// Sort by age and redisplay vector contents
std::sort(personVect.begin(),personVect.end(),age_sort());
std::cout << "\n\nWriting contents of VECTOR container (age sort): " << std::endl;
std::copy(personVect.begin(),personVect.end(),
std::ostream_iterator<person>(std::cout,"\n"));
// Resort by default and redisplay vector contents
std::sort(personVect.begin(),personVect.end(),default_sort());
std::cout << "\n\nWriting contents of VECTOR container (default sort): " << std::endl;
std::copy(personVect.begin(),personVect.end(),
std::ostream_iterator<person>(std::cout,"\n"));
return 0;
}
Output: