Monday, June 20, 2011

A bit of C++0x lambda and vector of user defined type sorting

Here is a short example how to using lambdas for sorting vector of user defined types.

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

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; 
}; 
 
int main() 
{ 
    std::vector<Person> a = 
    {
        Person(10, "Person1"), 
        Person(12, "Person2"), 
        Person(12, "Person3") 
    }; 
     
    std::cout << "Before revers sort" << std::endl; 
    std::for_each(a.begin(), a.end(),  
        [](const Person& p) 
        { 
            std::cout << " Person age: " << p.age << " name: " << p.name << std::endl; 
        }); 
 
    std::sort(a.begin(), a.end(),  
        [](const Person& p1, const Person& p2) 
        { 
            if (p1.age > p2.age) return true; 
            if (p1.name.compare(p2.name) > 0) return true; 
            return false; 
        }); 
 
    std::cout << "After revers sort" << std::endl; 
    std::for_each(a.begin(), a.end(),  
        [](const Person& p) 
        { 
            std::cout << " Person age: " << p.age << " name: " << p.name << std::endl; 
        }); 
}