Advantages of Using Algorithms in C++

Algorithms require move operators not to throw

All algorithms use std::swap() and std::move() when moving elements around, but only if the move constructor and move assignment are marked noexcept. Therefore, it is important to have these implemented for heavy objects when using algorithms. If they are not available and exception free, the elements will be copied instead.

Note: If we implement a move constructor and a move assignment operator in our class, std::swap() will utilize them and, therefore, a specified std::swap() overload is not needed.

Algorithms have complexity guarantees

Each algorithm’s complexity in the standard library is specified using big OO notation. Algorithms are created with performance in mind. Therefore, they do not allocate memory nor do they have a time complexity higher than O(n log n)O(n \space log\space n). Algorithms that do not fit these criteria are not included even if they are fairly common operations.

Remember: Note the exceptions of stable_sort(), inplace_merge(), and stable_partition(). Many implementations tend to temporarily allocate memory during these operations.

For example, let’s consider an algorithm that tests whether a non-sorted range contains duplicates. One option is to implement it by iterating through the range and search the rest of the range for a duplicate. This will result in an algorithm with O(n2)O(n^2) complexity:

Get hands-on with 1200+ tech skills courses.