lambda - print-out array and add comment
Sure! Here is an example of how you can use a lambda function in C++ to print out an array and add a comment for each element:
#include <iostream>
#include <array>
#include <algorithm>
int main() {
std::array<int, 5> arr = {1, 2, 3, 4, 5};
// Using a lambda function to print out the array and add a comment for each element
std::for_each(arr.begin(), arr.end(), [](int elem) {
std::cout << "Element: " << elem << " - Comment: This is element " << elem << std::endl;
});
return 0;
}
Explanation:
- We include the necessary header files,
iostream
,array
, andalgorithm
, to use the necessary functions and data types. - We define the
main
function as the entry point of the program. - We create an
std::array
namedarr
of typeint
with a size of 5 and initialize it with the values 1, 2, 3, 4, and 5. - We use the
std::for_each
algorithm function to iterate over each element in the array. - Within the lambda function, we define the parameter
elem
to represent each element in the array. - Inside the lambda function, we use
std::cout
to print out the element and add a comment for each element using the<<
operator. - Finally, we return 0 to indicate successful execution of the program.
This program will output:
Element: 1 - Comment: This is element 1
Element: 2 - Comment: This is element 2
Element: 3 - Comment: This is element 3
Element: 4 - Comment: This is element 4
Element: 5 - Comment: This is element 5
I hope this helps! Let me know if you have any further questions.