Tuesday, March 3, 2009

c++ stl - for_each, custom function and custom sort

//Author: Darius Kucinskas (c) 2008-2009
//Email: d[dot]kucinskas[eta]gmail[dot]com
//Blog: http://blog-of-darius.blogspot.com/
//License: GPL

#include <algorithm>
#include <vector>
#include <iostream>
#include <iterator>
#include <functional>

class Person
{
public:
  Person();
  Person(int a, std::string n);
  Person(const Person& src);

  int age;
  std::string name;
};

Person::Person()
: age(0)
, name("")
{};

Person::Person(int a, std::string n)
: age(a)
, name(n)
{};

Person::Person(const Person& src)
{
  age = src.age;
  name = src.name;
};

struct PersonPrint : public std::unary_function<Person, void>
{
  void operator() (Person p)
  {
    std::cout << " Person age: " << p.age << " name: " << p.name << std::endl;
  }
};

struct PersonGreater : public std::binary_function<Person, Person, bool>
{
  bool operator()(const Person& p1, const Person p2)
  {
    if (p1.age > p2.age) return true;
    if (p1.name.compare(p2.name) > 0) return true;
    return false;
  }
};

int main(int count, char** args)
{
  // for_each and custom unary function
  std::vector<Person> personVec;
  Person p1(10, "Person1");
  Person p2(12, "Person2");
  Person p3(12, "Person3");

  personVec.push_back(p1);
  personVec.push_back(p2);
  personVec.push_back(p3);
  
  std::cout << "before sort: " << std::endl;
  std::for_each(personVec.begin(), personVec.end(), PersonPrint());
  std::sort(personVec.begin(), personVec.end(), PersonGreater());
  std::cout << "after: " << std::endl;
  std::for_each(personVec.begin(), personVec.end(), PersonPrint());
}