Advantages of Using Algorithms in C++
Learn about the advantages of using algorithms in C++ for performance.
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 specifiedstd::swap()
overload is not needed.
Algorithms have complexity guarantees
Each algorithm’s complexity in the standard library is specified using big notation. Algorithms are created with performance in mind. Therefore, they do not allocate memory nor do they have a time complexity higher than . 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()
, andstable_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 complexity:
Get hands-on with 1400+ tech skills courses.