The <algorithm> header in C++ is a part of the Standard Template Library (STL) and provides a rich collection of functions for performing a variety of algorithmic operations on sequences. These algorithms are generic and operate on ranges defined by iterators, making them applicable to different container types (like vectors, lists, arrays, etc.) and even raw arrays.
In this comprehensive guide, we'll explore the functions provided by <algorithm>, how to use them, and discuss the differences between similar functions.
Table of Contents
- Introduction to
<algorithm>
- Iterators and Range Concepts
- Non-Modifying Sequence Operations
- Modifying Sequence Operations
- Partitioning Operations
- Sorting Operations
- Binary Search Operations
- Merge and Set Operations
- Heap Operations
- Min/Max Operations
- Permutation Operations
- Notes on Using Algorithms Efficiently
- Conclusion
1. Introduction to <algorithm>
The <algorithm> header provides functions that perform:
- Searching
- Sorting
- Modifying
- Partitioning
- Merging
These functions are designed to be efficient and work seamlessly with STL containers and custom data types, provided the necessary operators or comparison functions are defined.
2. Iterators and Range Concepts
Algorithms in <algorithm> operate on ranges defined by pairs of iterators:
- Input Iterators: For reading data.
- Output Iterators: For writing data.
- Forward Iterators: For single-pass algorithms.
- Bidirectional Iterators: For algorithms that require traversal in both directions.
- Random Access Iterators: For algorithms that require direct access by index.
Understanding the type of iterators required by each algorithm is crucial for their correct usage.
3. Non-Modifying Sequence Operations
These algorithms do not alter the elements in the sequences they operate on.
3.1 std::for_each
Usage: Applies a function to each element in a range.
std::for_each(first, last, func);
Example:
std::vector<int> vec = {1, 2, 3, 4, 5};
std::for_each(vec.begin(), vec.end(), [](int& n) { n *= 2; });
// vec now contains {2, 4, 6, 8, 10}
3.2 std::find
Usage: Searches for the first occurrence of a value.
auto it = std::find(first, last, value);
Example:
auto it = std::find(vec.begin(), vec.end(), 3);
if (it != vec.end()) {
// Found the element
}
3.3 std::find_if and std::find_if_not
Usage: Searches for the first element satisfying a predicate.
auto it = std::find_if(first, last, predicate);
Differences:
std::find_if finds the first element for which the predicate returns true.
std::find_if_not finds the first element for which the predicate returns false.
3.4 std::all_of, std::any_of, std::none_of
Usage:
std::all_of: Checks if all elements satisfy a condition.
std::any_of: Checks if any element satisfies a condition.
std::none_of: Checks if none of the elements satisfy a condition.
Example:
bool all_positive = std::all_of(vec.begin(), vec.end(), [](int n) { return n > 0; });
3.5 std::count and std::count_if
Usage:
std::count: Counts the number of elements equal to a value.
std::count_if: Counts the number of elements satisfying a predicate.
Example:
int count_twos = std::count(vec.begin(), vec.end(), 2);
int count_even = std::count_if(vec.begin(), vec.end(), [](int n) { return n % 2 == 0; });
4. Modifying Sequence Operations
These algorithms modify the elements or the structure of the sequence.
4.1 std::copy and std::copy_n
Usage: Copies elements from one range to another.
std::copy(first, last, destination);
std::copy_n(first, n, destination);
Example:
std::vector<int> vec2(vec.size());
std::copy(vec.begin(), vec.end(), vec2.begin());
4.2 std::move
Usage: Moves elements from one range to another, transferring ownership.
std::move(first, last, destination);
4.3 std::transform
Usage: Applies a function to each element and stores the result in a new range.
std::transform(first, last, destination, unary_op);
Example:
std::vector<int> squared(vec.size());
std::transform(vec.begin(), vec.end(), squared.begin(), [](int n) { return n * n; });
4.4 std::replace, std::replace_if, std::replace_copy, std::replace_copy_if
Usage:
std::replace: Replaces all elements equal to a value.
std::replace_if: Replaces all elements satisfying a predicate.
std::replace_copy: Copies elements to a new range, replacing certain values.
std::replace_copy_if: Copies elements to a new range, replacing elements satisfying a predicate.
Differences:
replace modifies in-place.
replace_copy copies to a new range without modifying the original.
4.5 std::fill and std::fill_n
Usage: Assigns a value to a range of elements.
std::fill(first, last, value);
std::fill_n(first, n, value);
4.6 std::generate and std::generate_n
Usage: Assigns values generated by a function.
std::generate(first, last, gen);
std::generate_n(first, n, gen);
Example:
int n = 0;
std::generate(vec.begin(), vec.end(), [&n]() { return n++; });
4.7 std::remove, std::remove_if, std::remove_copy, std::remove_copy_if
Usage:
std::remove: Removes elements equal to a value (logically).
std::remove_if: Removes elements satisfying a predicate (logically).
std::remove_copy: Copies elements to a new range, excluding certain values.
std::remove_copy_if: Copies elements to a new range, excluding elements satisfying a predicate.
Note: remove algorithms do not change the size of the container; they move the elements to the front and return an iterator to the new logical end. To actually remove elements, use the "erase-remove idiom":
vec.erase(std::remove(vec.begin(), vec.end(), value), vec.end());
4.8 std::unique and std::unique_copy
Usage:
std::unique: Removes consecutive duplicate elements.
std::unique_copy: Copies elements to a new range, omitting consecutive duplicates.
5. Partitioning Operations
These algorithms rearrange elements based on a condition.
5.1 std::partition and std::stable_partition
Usage:
std::partition: Reorders elements so that those satisfying a predicate come before others.
std::stable_partition: Same as std::partition but preserves the relative order of elements.
Differences:
std::partition may not preserve the relative order.
std::stable_partition is generally slower due to the ordering guarantee.
Example:
std::partition(vec.begin(), vec.end(), [](int n) { return n % 2 == 0; });
5.2 std::partition_copy
Usage: Copies elements into two separate ranges based on a predicate.
6. Sorting Operations
Algorithms for sorting sequences.
6.1 std::sort and std::stable_sort
Usage:
std::sort: Sorts elements in ascending order by default.
std::stable_sort: Same as std::sort but preserves the relative order of equal elements.
Differences:
std::sort does not guarantee the relative order of equal elements.
std::stable_sort ensures stability.
Example:
std::sort(vec.begin(), vec.end()); // Sorts in ascending order
std::sort(vec.begin(), vec.end(), std::greater<int>()); // Sorts in descending order
6.2 std::partial_sort
Usage: Partially sorts elements so that the first n elements are the smallest (sorted).
std::partial_sort(first, middle, last);
6.3 std::nth_element
Usage: Rearranges elements so that the element at the nth position is the element that would be in that position in a sorted sequence, and all elements before it are less, and all after are greater.
7. Binary Search Operations
Used on sorted ranges.
7.1 std::lower_bound, std::upper_bound, and std::equal_range
Usage:
std::lower_bound: Finds the first position where a value can be inserted without violating the ordering.
std::upper_bound: Finds the last position where a value can be inserted.
std::equal_range: Returns both lower_bound and upper_bound.
7.2 std::binary_search
Usage: Checks if a value exists in a sorted range.
8. Merge and Set Operations
Operate on sorted ranges.
8.1 std::merge
Usage: Merges two sorted ranges into a new range.
8.2 Set Algorithms
std::set_union: Combines elements from two sets.
std::set_intersection: Finds common elements.
std::set_difference: Elements in first set not in second.
std::set_symmetric_difference: Elements in one set or the other but not both.
Example:
std::vector<int> result;
std::set_union(vec1.begin(), vec1.end(), vec2.begin(), vec2.end(), std::back_inserter(result));
9. Heap Operations
Assuming the range represents a heap (a complete binary tree satisfying the heap property).
9.1 std::push_heap
Usage: Adds an element to the heap.
9.2 std::pop_heap
Usage: Removes the largest element from the heap.
9.3 std::make_heap
Usage: Rearranges elements into a heap.
9.4 std::sort_heap
Usage: Sorts a heap into ascending order.
10. Min/Max Operations
10.1 std::min, std::max, std::min_element, std::max_element
Usage:
std::min, std::max: Returns the smaller/larger of two values.
std::min_element, std::max_element: Finds the smallest/largest element in a range.
10.2 std::minmax and std::minmax_element
Usage: Returns both min and max in a single pass.
11. Permutation Operations
11.1 std::next_permutation and std::prev_permutation
Usage:
std::next_permutation: Transforms the range into the next lexicographical permutation.
std::prev_permutation: Transforms the range into the previous lexicographical permutation.
Example:
std::vector<int> vec = {1, 2, 3};
do {
// Process permutation
} while (std::next_permutation(vec.begin(), vec.end()));
12. Notes on Using Algorithms Efficiently
- Iterators: Ensure that the iterators used meet the requirements of the algorithm (e.g., random-access iterators for
std::sort).
- Container Compatibility: While most algorithms work with any container, some require specific iterator capabilities.
- Predicate Functions: Many algorithms accept predicates (functions returning
bool) or comparison functions. Ensure these are appropriately defined.
- Stability: When the order of equal elements matters, use the stable versions of algorithms (e.g.,
std::stable_sort).
- Performance: Be aware of the algorithm's complexity. For large data sets, prefer algorithms with better time complexity.
- Removing Elements: Remember that algorithms like
std::remove do not actually remove elements from containers. Use container member functions like erase in combination.
13. Conclusion
The <algorithm> header is a powerful tool in C++ programming, providing a wide range of functions to perform common algorithmic tasks efficiently. Understanding these algorithms, their requirements, and differences between similar functions allows you to write cleaner, more efficient, and more expressive code.
It's encouraged to explore each algorithm in detail and experiment with code examples to solidify your understanding. The cppreference.com website is an excellent resource for in-depth information on each function.
Further Reading and Practice:
- Experiment with different algorithms in code.
- Read more about iterator categories and their importance.
- Explore how custom comparison functions can be used.
- Learn about algorithms in
<numeric>, like std::accumulate and std::inner_product.
By mastering the algorithms provided in the <algorithm> header, you'll significantly enhance your abilities to manipulate and process data efficiently in C++.