Stefan Elmlund


Introduction to C++ STL Algorithms

C++ STL algorithms provide a standardized way to perform common operations on sequences of elements, such as arrays, vectors, and lists. These algorithms offer a high level of abstraction, promoting code reusability, readability, and maintainability. By leveraging the power of basic STL algorithms, developers can write more concise and expressive code while achieving better performance.

Basic STL Algorithms

std::sort:

std::sort is a versatile algorithm used for sorting elements in ascending order. It employs an efficient sorting technique, typically introsort or hybrid sorting algorithms like quicksort followed by insertion sort for small sequences.

std::vector<int> numbers = { 3, 1, 4, 1, 5, 9, 2, 6 };
std::sort(numbers.begin(), numbers.end());

// numbers: { 1, 1, 2, 3, 4, 5, 6, 9 }

std::find:

std::find searches for the first occurrence of a specified value in a sequence and returns an iterator pointing to that element. If the value is not found, it returns the end iterator.

std::vector<int> numbers = { 1, 2, 3, 4, 5 };
auto it = std::find(numbers.begin(), numbers.end(), 3);

// it points to the element containing 3

auto it2 = std::find(number.begin(), number.end(), 6);

// it2 pointes to the number.end() iterator.

std::accumulate:

std::accumulate computes the sum (or the result of a specified binary operation) of all elements in a sequence. It’s a powerful algorithm for performing various types of accumulations, such as summation, product calculation, and custom operations.

std::vector<int> numbers = { 1, 2, 3, 4, 5 };
int sum = std::accumulate(numbers.begin(), numbers.end(), 0);

// sum: 15 (1 + 2 + 3 + 4 + 5)

std::copy:

std::copy copies elements from a source range to a destination range. It’s particularly useful for tasks like copying elements between different containers or extracting subsets of data.

std::vector<int> source = { 1, 2, 3, 4, 5 };
std::vector<int> destination(5);

std::copy(source.begin(), source.end(), destination.begin());

// destination: { 1, 2, 3, 4, 5 }

Advanced STL Algorithms

std::binary_search determines whether a specified value exists in a sorted sequence. It uses the binary search algorithm, offering logarithmic time complexity for searching operations.

std::vector<int> numbers = {1, 2, 3, 4, 5};
bool found = std::binary_search(numbers.begin(), numbers.end(), 3);

// found: true

std::transform:

std::transform is a versatile algorithm that applies a given function to each element in a sequence, producing a new sequence with the transformed elements. Its flexibility makes it invaluable for tasks such as element-wise operations, data normalization, and mathematical transformations.

std::vector<int> numbers = { 1, 2, 3, 4, 5 };
std::vector<int> squared_numbers;

std::transform(numbers.begin(), numbers.end(), std::back_inserter(squared_numbers),
               [](int x) { return x * x; });

// squared_numbers: { 1, 4, 9, 16, 25 }

std::merge:

std::merge combines two sorted sequences into a single sorted sequence. This algorithm is essential for tasks like merging sorted arrays or implementing merge sort efficiently.

std::vector<int> vec1 = { 1, 3, 5 };
std::vector<int> vec2 = { 2, 4, 6 };
std::vector<int> merged;

std::merge(vec1.begin(), vec1.end(), vec2.begin(), vec2.end(), std::back_inserter(merged));

// merged: { 1, 2, 3, 4, 5, 6 }

std::inplace_merge:

std::inplace_merge merges two sorted ranges in-place, producing a single sorted range. This algorithm is particularly useful when dealing with sorted containers like vectors or lists and can improve performance by avoiding extra memory allocations.

std::vector<int> vec = { 3, 1, 4, 1, 5, 9, 2, 6 };
std::sort(vec.begin(), vec.end());
std::inplace_merge(vec.begin(), vec.begin() + 4, vec.end());

// vec: { 1, 1, 2, 3, 4, 5, 6, 9 }

std::partition:

std::partition rearranges the elements in a sequence such that all elements satisfying a given predicate appear before those that don’t. This algorithm is useful for tasks like partitioning data based on certain criteria or implementing quicksort’s partition step.

std::vector<int> numbers = { 1, 2, 3, 4, 5, 6 };
auto is_even = [](int x) { return x % 2 == 0; };

std::partition(numbers.begin(), numbers.end(), is_even);

// numbers: { 2, 4, 6, 1, 3, 5 }

std::nth_element:

std::nth_element partially sorts a sequence such that the element at the nth position is in its sorted position, and all elements before it are less than or equal to it, and all elements after it are greater than or equal to it. This algorithm is beneficial for finding the median or selecting the top k elements efficiently.

std::vector<int> numbers = { 3, 1, 4, 1, 5, 9, 2, 6};
std::nth_element(numbers.begin(), numbers.begin() + 3, numbers.end());

// numbers: {1, 1, 2, 3, 5, 9, 4, 6}
// The element at index 3 (4th element) is in its sorted position

Conclusion

STL algorithms form the cornerstone of efficient C++ programming. By mastering these fundamental tools, developers can write cleaner, more expressive code while benefiting from improved performance and productivity. Whether you’re sorting elements, searching for specific values, performing accumulations, or copying data, basic STL algorithms provide a standardized and efficient solution. As you continue your journey in C++ programming, remember to leverage the power of basic STL algorithms to simplify your code and tackle a wide range of programming tasks effectively.