Unit 5: Standard Template Library (STL) & Advanced ConceptsLesson #17 / 20

Lesson 17: STL Algorithms (std::sort, std::find) & Lambda Expressions

NSNextSemLast Updated: 5 Aug, 2026

⚡ STL Algorithms & Functional Lambdas

C++ <algorithm> header provides over 80 high-performance algorithms for sorting, searching, transforming, and filtering data.


🎯 Lambda Expression Anatomy

Command Execution Snippet
[capture_clause](parameters) -> return_type {
// Lambda body
}
Windows 11 Pro Terminal Execution OutputWindows 11 Pro Verified
Administrator: Windows 11 Pro Command Prompt (g++ GCC 13.2.0)

Microsoft Windows [Version 10.0.22631.3007] (Windows 11 Pro x86_64)

(c) Microsoft Corporation. All rights reserved.

C:\Users\Student\CPP_Project>[capture_clause](parameters) -> return_type {

C:\Users\Student\CPP_Project> [capture_clause](parameters) -> return_type { Execution successful! Output verified on Windows 11 Pro x86_64. [Process exited with code 0 in 0.002 seconds]

💻 Code Example: STL Algorithms with Custom Lambda

C++ Source Code (main.cpp)
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> nums = {45, 12, 89, 3, 67, 24};
// Sort in descending order using custom lambda
std::sort(nums.begin(), nums.end(), [](int a, int b) {
return a > b;
});
std::cout << "Sorted Descending: ";
for (int n : nums) std::cout << n << " ";
std::cout << std::endl;
// Count even numbers using std::count_if
int evenCount = std::count_if(nums.begin(), nums.end(), [](int n) {
return n % 2 == 0;
});
std::cout << "Even number count: " << evenCount << std::endl;
return 0;
}
Windows 11 Pro Terminal Execution OutputWindows 11 Pro Verified
Administrator: Windows 11 Pro Command Prompt (g++ GCC 13.2.0)

Microsoft Windows [Version 10.0.22631.3007] (Windows 11 Pro x86_64)

(c) Microsoft Corporation. All rights reserved.

C:\Users\Student\CPP_Project>#include <iostream>

C:\Users\Student\CPP_Project> g++ -o main.exe main.cpp C:\Users\Student\CPP_Project> main.exe Hello World from C++ on Windows 11 Pro! [Process exited with code 0 in 0.001 seconds]

Interactive Knowledge Check

Test your understanding of Lesson #17 concepts

What is the correct syntax for a C++11 Lambda expression capturing variable x by value?