AnyCompiler

Lambdas y Algorithms

<algorithm> provee operaciones ya hechas como std::sort que funcionan sobre el par de iterators begin()/end() de cualquier container, en vez de que tú escribas un loop de ordenamiento a mano.

#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 

Expresiones lambda

Una lambda, escrita [capture](params) { body }, es una función anónima inline — la lista [capture] indica qué variables del entorno puede ver. Combinada con un algorithm como std::find_if, una lambda te permite expresar una condición personalizada sin escribir una función con nombre separada solo para ese único uso.

#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

Siguiente: smart pointers — la alternativa moderna, basada en RAII, a new y delete manuales.

Practice exercise

Dado vector<int> numbers = {1, 2, 3, 4}, construye un nuevo vector que contenga cada número elevado al cuadrado, luego imprímelos todos separados por espacios.