Friday, June 17, 2011

A bit of C++0x lambda and vector sort (reverse sort)

Here is example how to sort vector by using lambdas (You can compare it with old post where used std::greater() for this, in my opinion lambdas are cleaner).

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

int main()
{
    std::vector<int> a = { 10, 90, 50, 20, 30, 5 };
    std::vector<int> b = { 10, 90, 50, 20, 30, 5 };

    std::sort(a.begin(), a.end(),
        [](const int& a, const int& b)
        {
            return a < b;
        });

    std::copy(a.begin(), a.end(), std::ostream_iterator<int>(std::cout, " "));
    std::cout << std::endl;

    std::sort(b.begin(), b.end(),
        [](const int& a, const int& b)
        {
            return a > b;
        });

    std::copy(b.begin(), b.end(), std::ostream_iterator<int>(std::cout, " "));
    std::cout << std::endl;
}