-4

So I have been into studying C++ a lot lately, but I can't quite grasp what [](int x) is referencing to in the code below. All I understand is that the [](int x) is being used as an argument to the "filter" function, but don't know the details of how it works. Any explanation would be appreciated!

Here is the code I'm referring to:

filter(numbers, [](int n) 
        {
        return n > 3;
        });

Here is the whole code for reference:

#include <iostream>
#include <vector>
#include <sstream>
using namespace std;

void print(const vector<int>& v) {
    for (int item : v) {
        cout << item << " ";
    }

    cout << endl;
}

vector<int> filter(vector<int> &numbers, bool(*shouldFilter)(int)) {
    vector<int> filtered;


    for (int n : numbers) {
        if (shouldFilter(n)) {
            filtered.push_back(n);
        }
    }

    return filtered;
}

bool isEven(int number) {
    return number % 2 == 0;
}

int main() {
    using namespace std;

    vector<int> numbers = { 1,2,3,4,5,6,7,8 };

    filter(numbers, [](int n) 
        {
        return n > 3;
        });

    for (int ele : filter(numbers, isEven))
    {
        cout << ele << " ";
    }

    return 0;
}


  • 1
    It's a "lambda expression". Essentially a function without a name. In this case it's a function that takes a single argument `int n`. https://docs.microsoft.com/en-us/cpp/cpp/lambda-expressions-in-cpp?view=msvc-170 – Loocid Jun 03 '22 at 03:45
  • This seems like a good signpost duplicate, since many people who have the question will not know the right terminology. – Karl Knechtel Jun 03 '22 at 03:48

0 Answers0