C++ algorithm

C++ <algorithm>: Sorting and Searching

Why write a complex sorting algorithm from scratch when C++ has already done it for you? The <algorithm> library is a powerful toolkit that contains highly optimized functions for sorting, searching, counting, and manipulating data inside containers like vectors and arrays.


1. The Power of Iterators

Most functions in the <algorithm> library do not take containers directly. Instead, they require iterators—pointers that dictate exactly where the algorithm should start and stop its operation.

Algorithm Sort Example

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

int main() { vector<int> nums = {42, 12, 85, 7};

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

for (int n : nums) { cout << n << " "; // Outputs: 7 12 42 85 }

return 0; }


2. Common Errors with <algorithm>

Error 1: Passing the Wrong Iterator Types

A common mistake is trying to mix data types. If you try to sort an old C-style array by passing vector iterators, the compiler will generate massive, terrifying error logs. For C-style arrays, you use pointers: sort(arr, arr + size);.

Error 2: Searching Unsorted Data

The library includes a blazing-fast function called binary_search(). However, binary search mathematically requires the data to be sorted first! If you run binary_search() on an unsorted vector, the program won't crash, but it will frequently return false even if the item genuinely exists in the list. Always sort() before you binary_search().

Error 3: Forgetting the Header

Many standard algorithms share names with custom functions you might write. If you use std::find or std::reverse without writing #include <algorithm>, the compiler won't recognize the functions.


Exercise

?

What is required before you can successfully use the `binary_search()` function on a vector?