# 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 specified`std::swap()`

overload is not needed.

## Algorithms have complexity guarantees

Each algorithmâ€™s complexity in the standard library is specified using big $O$ 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 \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(n^2)$ complexity:

Get hands-on with 1200+ tech skills courses.