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:
- Understand what STL algorithms are and why they are beneficial.
- Learn the usage and syntax of the
std::for_each
algorithm. - See how
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?
- Efficiency: STL algorithms are highly optimized and can make your code faster.
- Readability: They offer a clear and expressive way to handle data structures.
- Reusability: These algorithms have undergone extensive testing, ensuring reliability.
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:
- Initialization: A
std::vector
is initialized with values{1, 2, 3, 4, 5}
. - Calling
std::for_each
: We callstd::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.- Lambda function: This lambda function takes an integer
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
- Initialization: A vector of grades
{75, 85, 95, 80, 70}
is initialized. - Calculating the Mean: The sum of the grades is computed, and dividing by the vector size gives the mean.
- Normalizing the Grades: We use
std::for_each
to subtract the mean from each grade. Note that the lambda captures the mean by value. - Printing the Grades: Another call to
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:
- The purpose and benefits of using STL algorithms.
- The syntax and functionality of
std::for_each
. - How to apply
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.