WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

C++ · Intermediate · question 34 of 100

What is a lambda function in C++? Provide an example of its usage.?

📕 Buy this interview preparation book: 100 C++ questions & answers — PDF + EPUB for $5

A lambda function in C++ is a small anonymous function that can be defined inline with the code that uses it. It is similar to a regular function, but does not have a name and can be defined on-the-fly. Lambda functions can capture variables from their enclosing scope, and can be used as arguments to other functions or stored in variables.

Here’s an example of using a lambda function to sort a vector of integers:

    #include <iostream>
    #include <vector>
    #include <algorithm>
    
    using namespace std;
    
    int main() {
        vector<int> v = {5, 2, 8, 1, 9};
        
        // Sort the vector using a lambda function
        sort(v.begin(), v.end(), [](int a, int b) {
            return a < b;
        });
        
        // Print the sorted vector
        for (auto x : v) {
            cout << x << " ";
        }
        cout << endl;
        
        return 0;
    }

In this example, we define a lambda function inside the sort function call that compares two integers and returns true if the first one is less than the second one. We then pass this lambda function as the third argument to the sort function, which sorts the vector in ascending order.

Lambda functions are particularly useful when we need to define a small piece of code that is only used once, or when we need to customize the behavior of a function in a specific way. They are a powerful feature of modern C++, and can make our code more expressive and concise.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic C++ interview — then scores it.
📞 Practice C++ — free 15 min
📕 Buy this interview preparation book: 100 C++ questions & answers — PDF + EPUB for $5

All 100 C++ questions · All topics