AnyCompiler

Lambdas aur Algorithms

<algorithm>, std::sort jaisi ready-made operations deta hai jo kisi bhi container ke begin()/end() iterator pair par kaam karti hain, aapko khud hand se ek sorting loop likhne ke bajaye.

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

int main() {
    vector<int> numbers = {5, 2, 8, 1, 9};
    sort(numbers.begin(), numbers.end());

    for (int n : numbers) {
        cout << n << " ";
    }
    cout << endl;
    return 0;
}
Output
1 2 5 8 9 

Lambda expressions

Ek lambda, jo [capture](params) { body } se likha jaata hai, ek anonymous inline function hai — [capture] list batati hai ki woh surrounding mein kaun se variables dekh sakta hai. std::find_if jaise ek algorithm ke saath combine karke, ek lambda aapko sirf us ek use ke liye ek separate named function likhe bina ek custom condition express karne deta hai.

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

int main() {
    vector<int> numbers = {1, 2, 3, 4, 5};
    int threshold = 3;

    auto it = find_if(numbers.begin(), numbers.end(), [threshold](int n) {
        return n > threshold;
    });

    if (it != numbers.end()) {
        cout << "First number greater than " << threshold << " is " << *it << endl;
    }
    return 0;
}
Output
First number greater than 3 is 4

Aage: smart pointers — manual new aur delete ka modern, RAII-based alternative.

Practice exercise

Ek vector<int> numbers = {1, 2, 3, 4} diya gaya hai, ek naya vector banao jisme har number ka square ho, phir sabko spaces se separate karke print karo.