Master lambda expressions, STL algorithms, and object-oriented inheritance.
Write modern, functional C++ and leverage OOP principles.
[capture](parameters) -> return_type {
// body
}[] - capture clause (variables from outer scope)() - parameters (like regular functions)-> type - return type (optional, usually inferred)auto greet = []() { cout << "Hello!"; };
greet(); // Prints: Hello!
auto add = [](int a, int b) { return a + b; };
cout << add(3, 4); // Prints: 7int x = 10;
auto byValue = [x]() { return x; }; // Copy
auto byRef = [&x]() { x++; }; // Reference
auto allByValue = [=]() { return x; }; // All by copy
auto allByRef = [&]() { x++; }; // All by refvector nums = {1, 2, 3, 4, 5};
for_each(nums.begin(), nums.end(), [](int n) {
cout << n * 2 << " ";
}); Simple lambda: 7
With capture: 15
Modified by ref: 11
Doubled: 2 4 6 8 10
auto f = []() { };auto f = [](int x) { return x; };[x], reference: [&x][=] by value, [&] by refReview feedback below
#include <algorithm>vector v = {5, 2, 8, 1, 9};
sort(v.begin(), v.end()); // Ascending
sort(v.begin(), v.end(), greater()); // Descending auto it = find(v.begin(), v.end(), 5);
if (it != v.end()) cout << "Found!";
bool exists = binary_search(v.begin(), v.end(), 5);// Transform each element
transform(v.begin(), v.end(), v.begin(),
[](int x) { return x * 2; });
// Copy elements matching condition
vector evens;
copy_if(v.begin(), v.end(), back_inserter(evens),
[](int x) { return x % 2 == 0; }); #include
int sum = accumulate(v.begin(), v.end(), 0);
int count = count_if(v.begin(), v.end(),
[](int x) { return x > 5; }); Sorted: 1 2 3 4 5
Found 3 at position 2
Sum: 15
Count > 2: 3
sort(v.begin(), v.end());find(v.begin(), v.end(), value);accumulate(v.begin(), v.end(), 0);count_if(begin, end, predicate);Review feedback below
class Animal {
public:
virtual void speak() {
cout << "Animal sound" << endl;
}
virtual ~Animal() {} // Virtual destructor
};virtual enables runtime polymorphismclass Dog : public Animal {
public:
void speak() override {
cout << "Woof!" << endl;
}
};
class Cat : public Animal {
public:
void speak() override {
cout << "Meow!" << endl;
}
};: public Animal inherits from Animaloverride ensures we're overriding a virtual functionAnimal* pet = new Dog();
pet->speak(); // Prints "Woof!" (dynamic dispatch)
delete pet;Dog says: Woof!
Cat says: Meow!
Using base pointer:
Woof!
Meow!
virtual void func() { }class Derived : public Base { }void func() override { }virtual ~Base() {}Review feedback below