std::for_each()

head File

#include <algorithm>

When given a container scope, we usually need to perform the same operation on every element in it. Such operations might include printing the element, modifying an element's value, or applying a custom function, among others. In the C++ Standard Library, the std::for_each() algorithm function provides a convenient way to perform a specified operation on the elements within the bounds of a container.

The std::for_each() function takes three arguments: the starting iterator for the given range, the ending iterator, and a callable object. It does this by looping through each element in the range and passing that element to a callable object for processing.

function prototype

template< class InputIt, class UnaryFunction >
UnaryFunction for_each( InputIt first, InputIt last, UnaryFunction f );

Parameter analysis

first and last are a pair of iterators representing ranges, representing the range of elements to traverse. The range is the left-closed right-open interval [first, last).

f is a callable object (function, function object, or lambda expression) that will be applied to each element in the scope.

usage

#include <iostream>
#include <vector>
#include <algorithm>
 
// 定义一个函数对象
struct PrintElement {
    
    
    void operator()(int x) const {
    
    
        std::cout << x << " ";
    }
};
 
int main() {
    
    
    std::vector<int> nums = {
    
    1, 2, 3, 4, 5};
 
    // 使用函数对象打印每个元素
    std::for_each(nums.begin(), nums.end(), PrintElement());
 
    return 0;
}

The output is: 1 2 3 4 5

In this example, we define a function object named PrintElement and overload the parenthesis operator so that it can be called like a function. An instance of PrintElement is passed to the std::for_each() function as the operation function. On each call, it prints the value of the current element to the standard output stream.

When using the std::for_each() function, we can choose to use a function object, a function pointer, or a Lambda expression as the operation function. Whichever way we choose, std::for_each() automatically iterates over each element within the bounds of the container, and passes each element to the operator function for processing.

To summarize, std::for_each() is a very convenient arithmetic function that can be used to perform the same operation on the elements of a container. By passing the operation function into std::for_each(), we can avoid writing loops manually and improve the readability and conciseness of the code.

Guess you like

Origin blog.csdn.net/qq_36314864/article/details/132086118