How to use a lambda expression and the generate() function In C++
Create and initialize a list in C++ STL with a lambda expression and the generate() function. The lambda expression captures variables and defines the logic for generating values. By applying the generate() function to the list range, the generated values are to be assigned to the respective list of elements. This approach provides a concise and efficient way to populate a list with custom-generated values.
Syntax
std::generate(list.begin(), list.end(), [&]() { /* lambda expression */ });
Example
C++
#include <iostream> #include <list> #include <algorithm> int main() { std::list< int > myList(5); int value = 1; std::generate(myList.begin(), myList.end(), [&value]() { return value++; }); // Print the contents of the list for ( const auto & element : myList) { std::cout << element << " " ; } std::cout << std::endl; return 0; } |
Output:
1 2 3 4 5
Different Ways to Initialize a List in C++ STL
Prerequisite: List in C++
Lists are sequence containers that allow non-contiguous memory allocation The following are the different ways to create and initialize a List in C++ STL.
- Initializing an empty List and pushing values one by one
- Specifying List size and initializing all values
- Initializing List like the arrays
- Initializing a list from an array
- Initializing a list from a vector
- Initializing a list from another List
- Initializing the List using the fill() function
- Using a lambda expression and the generate() function: