Back to C++
2025-12-315 min read

C++ <algorithm>

Learn C++ <algorithm> step by step with clear examples and exercises.

Title: Mastering C++ Algorithms: A full guide to Library

Why This Matters

The C++ Standard Template Library (STL) is a powerful tool for developers, and the library is its core component. This library offers numerous functions that help perform common operations on data efficiently, making it an essential part of any C++ programmer's arsenal. Understanding the library will not only help you solve complex programming problems but also prepare you for coding interviews and real-world development scenarios.

Prerequisites

To follow this guide, you should have a good understanding of:

  1. Basic C++ syntax and data structures (arrays, vectors, lists)
  2. Functions and function templates
  3. Namespaces
  4. Compiler flags (e.g., -std=c++11)

Core Concept

The library provides a wide range of functions for sorting, searching, manipulating sequences, and performing mathematical operations on iterators. The library is divided into several header files, with the most commonly used one being ``.

Iterators

Iterators are essential when working with the library. They allow you to traverse containers (such as arrays, vectors, or lists) and access their elements. C++ provides four types of iterators:

  1. Input iterator: Read-only access to elements
  2. Output iterator: Write-only access to elements
  3. Forward iterator: Both read and write access to elements in the forward direction
  4. Bidirectional iterator: Access to elements in both directions (forward and backward)
  5. Random access iterator: Fast random access to elements with support for arithmetic operations

Key Algorithms

Some of the most important algorithms provided by the library are:

  1. sort(): Sorts a range of elements in ascending order
  2. reverse(): Reverses the order of elements in a range
  3. find() and find_if(): Find an element that matches a specified condition within a range
  4. count(): Counts the number of occurrences of a specific element in a range
  5. remove() and erase(): Removes elements from a container that match a specified condition
  6. replace(): Replaces elements in a container that match a specified condition with new values
  7. transform(): Applies a function to every element in a range
  8. min_element() and max_element(): Finds the minimum or maximum element in a range
  9. accumulate(): Computes the accumulated sum of a sequence using an associative binary operation
  10. search(): Searches for a subrange within a container
  11. merge(): Merges two sorted ranges into a single sorted range
  12. unique(): Removes duplicate elements from a sorted range

Worked Example

Let's consider an example where we have a vector of integers and want to sort it using the sort() algorithm:

#include <iostream>
#include <vector>
#include <algorithm>

int main() {
std::vector<int> numbers = {5, 3, 1, 4, 2};
std::cout << "Unsorted vector: ";
for (const auto& number : numbers) {
std::cout << number << ' ';
}
std::cout << '\n';

std::sort(numbers.begin(), numbers.end());
std::cout << "Sorted vector: ";
for (const auto& number : numbers) {
std::cout << number << ' ';
}
std::cout << '\n';

return 0;
}

Output:

Unsorted vector: 5 3 1 4 2
Sorted vector: 1 2 3 4 5

Common Mistakes

  1. Incorrect iterator ranges: Make sure to provide the correct iterator ranges when using algorithms. Forgetting to include end() or providing an invalid range can lead to unexpected results.
std::vector<int> numbers = {5, 3, 1, 4, 2};
std::sort(numbers.begin(), numbers.begin()); // Incorrect iterator range
  1. Compile-time errors: Ensure you use the correct header files and that your compiler is set to the correct C++ standard (e.g., -std=c++11).
  1. Using algorithms on unsorted data: Some algorithms, such as binary_search(), require the input range to be sorted. Using these functions on unsorted data will result in incorrect results or runtime errors.
  1. Not understanding iterator types: Understanding the differences between input iterators, output iterators, forward iterators, bidirectional iterators, and random access iterators is crucial for using the library effectively.

Practice Questions

  1. Write a program that finds all pairs of numbers in an array whose sum equals a given target value.
  2. Implement a function that removes duplicates from a sorted vector using the unique() algorithm.
  3. Write a program that sorts a list of strings lexicographically and then reverses the order of the words within each string.
  4. Implement a function that counts the number of occurrences of a specific element in a range using the count_if() algorithm.
  5. Write a program that finds the second smallest number in an array using the library.

FAQ

  1. Why can't I use the sort() function on a raw C-style array?
  • You can, but you must provide an additional iterator to indicate the end of the array (e.g., std::sort(myArray, myArray + sizeof(myArray) / sizeof(int));). It's recommended to use containers like vectors instead for better performance and ease of use.
  1. What is the difference between find() and find_if()?
  • find() finds the first occurrence of a specific element, while find_if() searches for an element that matches a specified condition defined by a function object or lambda expression.
  1. How can I sort a vector in descending order using the sort() algorithm?
  • You can use the std::greater<>() function object to sort the elements in descending order: std::sort(numbers.begin(), numbers.end(), std::greater());.
  1. What is the purpose of the accumulate() algorithm?
  • The accumulate() algorithm computes the accumulated sum of a sequence using an associative binary operation, such as addition or multiplication. It can be used to compute various aggregates, such as the product, minimum, maximum, or sum of elements in a range.
C++ &lt;algorithm&gt; | C++ | XQA Learn