In this tutorial, we will explore the powerful algorithms provided by the Standard Template Library (STL) in C++. These algorithms are essential for efficient data manipulation and are built on top of iterators, which you already know from the previous topic. Understanding these algorithms will significantly enhance your ability to write clean and optimized C++ code.
The STL provides a collection of generic functions that operate on sequences defined by iterators. These algorithms can be categorized into various groups such as sorting, searching, modifying, and numeric operations. Knowing how to use these algorithms effectively can greatly simplify your code and improve its performance.
In this tutorial, we will cover some of the most commonly used STL algorithms: sort, find, count, accumulate, transform, for_each, binary_search, min_element/max_element, copy, and reverse. Each algorithm has its own specific use case, and understanding them will help you write more efficient and readable code.
sortThe sort function is used to sort elements in a range. It uses the less-than operator by default but can also take a custom comparator function.
1#include <iostream>2#include <vector>3#include <algorithm>45int main() {6std::vector<int> numbers = {5, 2, 9, 1, 5, 6};78// Sort the vector in ascending order9std::sort(numbers.begin(), numbers.end());1011// Print sorted vector12for (int num : numbers) {13std::cout << num << " ";14}1516return 0;17}
findThe find function searches for a specific element in a range and returns an iterator to the first occurrence of that element.
1#include <iostream>2#include <vector>3#include <algorithm>45int main() {6std::vector<int> numbers = {5, 2, 9, 1, 5, 6};7int target = 5;89// Find the first occurrence of 'target' in the vector10auto it = std::find(numbers.begin(), numbers.end(), target);1112if (it != numbers.end()) {13std::cout << "Element found at position: " << std::distance(numbers.begin(), it) << std::endl;14} else {15std::cout << "Element not found" << std::endl;16}1718return 0;19}
accumulateThe accumulate function computes the sum of a range of elements, optionally using an initial value and a custom binary operation.
1#include <iostream>2#include <vector>3#include <numeric> // For std::accumulate45int main() {6std::vector<int> numbers = {1, 2, 3, 4, 5};78// Compute the sum of the vector elements9int sum = std::accumulate(numbers.begin(), numbers.end(), 0);1011std::cout << "Sum of elements: " << sum << std::endl;1213return 0;14}
transformThe transform function applies a given operation to each element in a range and stores the result in another range.
1#include <iostream>2#include <vector>3#include <algorithm> // For std::transform45int main() {6std::vector<int> numbers = {1, 2, 3, 4, 5};7std::vector<int> result(numbers.size());89// Square each element in the vector10std::transform(numbers.begin(), numbers.end(), result.begin(), [](int x) { return x * x; });1112// Print transformed vector13for (int num : result) {14std::cout << num << " ";15}1617return 0;18}
binary_searchThe binary_search function searches for a specific element in a sorted range and returns true if the element is found.
1#include <iostream>2#include <vector>3#include <algorithm> // For std::sort and std::binary_search45int main() {6std::vector<int> numbers = {1, 2, 3, 4, 5};7int target = 3;89// Sort the vector (required for binary search)10std::sort(numbers.begin(), numbers.end());1112// Perform binary search13if (std::binary_search(numbers.begin(), numbers.end(), target)) {14std::cout << "Element found" << std::endl;15} else {16std::cout << "Element not found" << std::endl;17}1819return 0;20}
copyThe copy function copies elements from one range to another.
1#include <iostream>2#include <vector>3#include <algorithm> // For std::copy45int main() {6std::vector<int> source = {1, 2, 3, 4, 5};7std::vector<int> destination(source.size());89// Copy elements from source to destination10std::copy(source.begin(), source.end(), destination.begin());1112// Print copied vector13for (int num : destination) {14std::cout << num << " ";15}1617return 0;18}
Let's create a complete program that demonstrates the use of several STL algorithms. This program will sort a vector, find an element, count occurrences, compute the sum, square each element, print all elements, perform a binary search, find the minimum and maximum elements, copy the vector, and reverse it.
1#include <iostream>2#include <vector>3#include <algorithm> // For various algorithms4#include <numeric> // For std::accumulate56void print(int x) {7std::cout << x << " ";8}910int main() {11std::vector<int> numbers = {5, 2, 9, 1, 5, 6};12int target = 5;1314// Sort the vector15std::sort(numbers.begin(), numbers.end());16std::cout << "Sorted vector: ";17for (int num : numbers) {18std::cout << num << " ";19}20std::cout << std::endl;2122// Find the first occurrence of 'target'23auto it = std::find(numbers.begin(), numbers.end(), target);24if (it != numbers.end()) {25std::cout << "Element found at position: " << std::distance(numbers.begin(), it) << std::endl;26} else {27std::cout << "Element not found" << std::endl;28}2930// Count the occurrences of 'target'31int count = std::count(numbers.begin(), numbers.end(), target);32std::cout << "Element " << target << " occurs " << count << " times." << std::endl;3334// Compute the sum of the vector elements35int sum = std::accumulate(numbers.begin(), numbers.end(), 0);36std::cout << "Sum of elements: " << sum << std::endl;3738// Square each element in the vector39std::vector<int> result(numbers.size());40std::transform(numbers.begin(), numbers.end(), result.begin(), [](int x) { return x * x; });41std::cout << "Squared elements: ";42for (int num : result) {43std::cout << num << " ";44}45std::cout << std::endl;4647// Print each element in the vector48std::cout << "Original vector: ";49std::for_each(numbers.begin(), numbers.end(), print);50std::cout << std::endl;5152// Perform binary search (vector must be sorted)53if (std::binary_search(numbers.begin(), numbers.end(), target)) {54std::cout << "Element found in binary search" << std::endl;55} else {56std::cout << "Element not found in binary search" << std::endl;57}5859// Find the minimum and maximum elements60auto min_it = std::min_element(numbers.begin(), numbers.end());61auto max_it = std::max_element(numbers.begin(), numbers.end());62std::cout << "Minimum element: " << *min_it << std::endl;63std::cout << "Maximum element: " << *max_it << std::endl;6465// Copy the vector66std::vector<int> copied(numbers.size());67std::copy(numbers.begin(), numbers.end(), copied.begin());68std::cout << "Copied vector: ";69for (int num : copied) {70std::cout << num << " ";71}72std::cout << std::endl;7374// Reverse the vector75std::reverse(copied.begin(), copied.end());76std::cout << "Reversed vector: ";77for (int num : copied) {78std::cout << num << " ";79}80std::cout << std::endl;8182return 0;83}
Sorted vector: 1 2 5 5 6 9 Element found at position: 2 Element 5 occurs 2 times. Sum of elements: 28 Squared elements: 1 4 25 25 36 81 Original vector: 1 2 5 5 6 9 Element found in binary search Minimum element: 1 Maximum element: 9 Copied vector: 1 2 5 5 6 9 Reversed vector: 9 6 5 5 2 1
In this tutorial, we covered several important STL algorithms:
Understanding these algorithms and how to use them effectively will greatly enhance your ability to write efficient and clean C++ code.
In the next tutorial, we will explore functors (function objects) in C++. Functors are objects that can be called like functions and are often used with STL algorithms to provide more flexible behavior. This will further expand your toolkit for writing powerful and reusable C++ programs.
Stay tuned!