C++ Algorithms

C++ Algorithms: Built-In Power

The final piece of the STL puzzle is the Algorithms library. The C++ standard library includes dozens of powerful algorithms for searching, sorting, counting, and manipulating data.

Instead of writing complex sorting logic yourself, you can use these highly optimized functions!


1. Using Algorithms

To use them, you must include the <algorithm> library. Most algorithms take Iterators as their arguments to define the start and end points of the data you want to process.

Common Algorithms:

Algorithm Example

#include <iostream>
#include <vector>
#include <algorithm> // Include algorithms!
using namespace std;

int main() { vector<int> numbers = {50, 20, 90, 10, 30};

// 1. Sort the vector (from beginning to end) sort(numbers.begin(), numbers.end());

cout << "Sorted: "; for(int n : numbers) cout << n << " "; // Output: 10 20 30 50 90

cout << "\n";

// 2. Reverse the vector reverse(numbers.begin(), numbers.end());

cout << "Reversed: "; for(int n : numbers) cout << n << " "; // Output: 90 50 30 20 10

return 0; }


2. Why Iterators Matter Here

Because the sort() function expects iterators as arguments (numbers.begin() and numbers.end()), you can technically use the exact same sort() function to sort a vector, an array, or a deque! This is the brilliance of the C++ STL—functions are decoupled from the containers they operate on.


Exercise

?

Which header file must be included to use the sort() function?