CPP/C++0x/Lambda
From ProgrammingExamples
< CPP
Lambda.cpp
#include <iostream> #include <vector> #include <algorithm> #include <utility> void Lambda(); void Equivalent(); int main() { } void Lambda() { std::vector<std::pair<int, float> > v{ {1, 4.5}, {3, 6.7}, {9, 7.8} }; auto it=std::find_if(v.begin(), v.end(), [](std::pair<int, float> p) { return p.first==3; }); // This lambda expression (or "anonymous function") lets you "on the fly" define a function to be used. // Here, we are comparing the .first of all of the items in the container to "3" std::cout << it->second; } struct Equals { Equals(const int value) { CompareValue = value; } bool operator()(const std::pair<int, float>& value) { return value.first == 3; } int CompareValue; }; void Equivalent() { std::vector<std::pair<int, float> > v{ {1, 4.5}, {3, 6.7}, {9, 7.8} }; // This works, but this following is shorter: // Equals myEquals; // myEquals.CompareValue = 3; // auto it=std::find_if(v.begin(), v.end(), myEquals); auto it=std::find_if(v.begin(), v.end(), Equals(3)); std::cout << it->second; }
CMakeLists.txt
cmake_minimum_required(VERSION 2.6) Project(Lambda) ADD_EXECUTABLE(Lambda Lambda.cpp)