Welcome to the introduction to Standard Template Library (STL) algorithms in C++! In today's fast-paced development environment, efficiency and maintainability are crucial. Using tools like STL algorithms can help you achieve these goals by providing pre-built, robust functions.
By the end of this lesson, you will:
std::for_each
algorithm.std::for_each
can be used in a practical example.STL algorithms are a collection of functions provided by the Standard Template Library (STL) in C++. They perform common operations on sequences of data. Using STL algorithms saves time and effort by leveraging well-tested and optimized operations for tasks like searching, sorting, and transforming data. Why Use STL Algorithms?
Some commonly used STL algorithms include:
std::for_each
: Applies a function to a range of elements.std::sort
: Sorts a range of elements.std::find
: Searches for a value in a range of elements.In this lesson, we will focus on std::for_each
.
std::for_each
lets you execute a specified function on every element within a range. Here is its basic signature:
C++1std::for_each(InputIterator first, InputIterator last, Function fn);
InputIterator first
: An iterator pointing to the start of the range.InputIterator last
: An iterator pointing to one past the end of the range.Function fn
: A function or function object (often a lambda) to apply to the elements in the range.This function is especially useful when you need to perform operations on all elements of a container, such as displaying, modifying, or accumulating values.
Here’s a basic example demonstrating the usage of std::for_each
to print elements of a vector:
C++1#include <iostream> 2#include <vector> 3#include <algorithm> 4 5int main() { 6 std::vector<int> data = {1, 2, 3, 4, 5}; 7 8 // Applying std::for_each 9 std::for_each(data.begin(), data.end(), [](int n) { 10 std::cout << n << ' '; 11 }); 12 std::cout << '\n'; // Output: 1 2 3 4 5 13 14 return 0; 15}
Explanation of the Code:
std::vector
is initialized with values {1, 2, 3, 4, 5}
.std::for_each
: We call std::for_each
with three arguments:
data.begin()
: An iterator pointing to the beginning of the vector.data.end()
: An iterator pointing to one past the end of the vector.n
and prints it, followed by a space.When std::for_each
is executed, the lambda function is called for each element, resulting in the elements being printed to the console.
Imagine you have a list of grades, and you want to normalize them by subtracting the mean. Here's how you could use std::for_each
to accomplish this:
C++1#include <iostream> 2#include <vector> 3#include <algorithm> 4 5int main() { 6 std::vector<int> grades = {75, 85, 95, 80, 70}; 7 8 // Calculate the mean 9 double sum = 0; 10 for (int grade : grades) { 11 sum += grade; 12 } 13 double mean = sum / grades.size(); // mean = 81.0 14 15 // Normalize the grades by subtracting the mean 16 std::for_each(grades.begin(), grades.end(), [mean](int &grade) { 17 grade -= mean; 18 }); 19 20 // Print the normalized grades 21 std::for_each(grades.begin(), grades.end(), [](int grade) { 22 std::cout << grade << ' '; 23 }); 24 std::cout << '\n'; // Output: -6 4 14 -1 -11 25 26 return 0; 27}
Explanation of the Real-World Example
{75, 85, 95, 80, 70}
is initialized.std::for_each
to subtract the mean from each grade. Note that the lambda captures the mean by value.std::for_each
prints the normalized grades.By using std::for_each
, we applied a custom operation to each element in the vector seamlessly.
We have covered the essentials of STL algorithms in C++, focusing on std::for_each
. We learned:
std::for_each
.std::for_each
in both simple and real-world scenarios.By leveraging STL algorithms, you can write more concise, readable, and efficient code. In the next section, you will get hands-on practice with std::for_each
, applying what you've learned and exploring more advanced use cases.