
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Lambda expression in C++
C++ STL includes useful generic functions like std::for_each. Unfortunately they can also be quite cumbersome to use, particularly if the functor you would like to apply is unique to the particular function. So this function that you'll create will be in that namespace just being used at that one place. The solution to this is using anonymous functions.
C++ has introduced lambda expressions in C++11 to allow creating anonymous function. For example,
Example
#include<iostream> #include<vector> #include <algorithm> // for_each using namespace std; int main() { vector<int> myvector; myvector.push_back(1); myvector.push_back(2); myvector.push_back(3); for_each(myvector.begin(), myvector.end(), [](int x) { cout << x*x << endl; }); }
Output
1 4 9
The (int x) is used to define the arguments that the lambda expression would be called with. The [] are used to pass variables from the local scope to the inner scope of the lambda, this is called capturing variables. These expressions if simple, can auto deduce their types. You can also explicitly provide type information using the following syntax
[](int x) -> double { return x/2.0; }
- Related Questions & Answers
- What is Lambda expression in C#?
- Lambda expression in Java 8
- What is a lambda expression in C++11?
- Java Lambda Expression with Collections
- Type Inference in Lambda expression in Java?
- How to write a conditional expression in lambda expression in Java?
- Importance of Predicate interface in lambda expression in Java?
- How to use BooleanSupplier in lambda expression in Java?
- How to use IntSupplier in lambda expression in Java?
- Differences between anonymous class and lambda expression in Java?
- Differences between Lambda Expression and Method Reference in Java?
- How to implement PropertyChangeListener using lambda expression in Java?
- How to implement DoubleConsumer using lambda expression in Java?
- How to implement IntBinaryOperator using lambda expression in Java?
- How to implement DoubleToIntFunction using lambda expression in Java?