Skip to content

Instantly share code, notes, and snippets.

@dazfuller
Created October 31, 2011 16:46
Show Gist options
  • Save dazfuller/1327971 to your computer and use it in GitHub Desktop.
Save dazfuller/1327971 to your computer and use it in GitHub Desktop.
Example use of Lambda expressions and for ranges with C++11
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
void FindValue(vector<string>& values, std::function<bool (const string&)> f)
{
auto i = find_if(values.begin(), values.end(), f);
if (values.end() == i)
{
cout << "Unable to find value" << endl;
}
else
{
cout << "Found: " << *i << endl;
}
}
vector<string> FindIfLength(const vector<string>& values, function<bool (const string&, const unsigned int)> f, const int length)
{
vector<string> results;
for (auto i : values)
{
if (f(i, length))
{
results.push_back(i);
}
}
return results;
}
int main (int argc, char** argv)
{
vector<string> v1 = { "Hello", "World", "Information"};
FindValue(v1, [] (const string& s) { return s == "Hello"; } );
FindValue(v1, [] (const string& s) { return s == "World"; } );
FindValue(v1, [] (const string& s) { return s == "Bob"; } );
for (auto s : FindIfLength(v1, [] (const string& s, const unsigned int i) -> bool { return s.length() >= i; }, 7))
{
cout << "Found: " << s << endl;
}
return 0;
}
@dazfuller
Copy link
Author

Compiled on Ubuntu 11.10 (GCC 4.6.1) using the following switches:

g++ --std=c++0x -Wall -Werror -O2 -o example example.cpp

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment