Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

Ergodic calculation method is commonly used

[Algorithm introduction] :

for_each; // Iterate over the container

transform; // Move elements from one container to another

 for_each(demo1.cpp)

【 Function 】 :

Implement traversal of the containerCopy the code

Function prototype:

    for_each(iterator begin, iterator end,_func);

// Start iterator // end iterator // _func function or function objectCopy the code

“Demo” :

// demo1.cpp
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;

// Define a normal function
void print01(int v)
{
    cout << "v = " << v << endl;
}

// Define a function object
class MyPrint
{
public:
    void operator(a)(int v)
    {
        cout << "v = "<< v << endl; }};// Basic usage of the for_each algorithm
void test01(a)
{
    vector<int> v;
    // Add elements to the container
    for (int i = 0; i < 10; i++)
    {
        v.push_back(i);
    }
    // go through the algorithm
    // Use normal functions for traversal
    for_each(v.begin(), v.end(), print01);
    cout << endl;
    // Use function objects for traversal
    for_each(v.begin(), v.end(), MyPrint());
}

int main(a)
{
    test01(a);return 0;
}
Copy the code

Note: for_each is the most commonly used traversal algorithm in real development

 transform(demo2.cpp)

【 Function 】 :

Move containers to another containerCopy the code

Function prototype:

transform(iterator begin1,iterator end1,iterator begin2,_func);

Begin1 start iterator of the source container // end1 end iterator of the source container // begin2 Start iterator of the target container // _func function or function objectCopy the code

“Demo” :

// demo2.cpp
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;

// Define a function object
class Transform
{
public:
    int operator(a)(int v)
    {
        returnv; }};// Define a function object
class MyPrint
{
public:
    void operator(a)(int v)
    { cout << v << endl; }};void test01(a)
{
    vector<int> v;
    for (int i = 0; i < 5; i++)
    {
        v.push_back(i);
    }
    vector<int> vTarget;
    // Create space in advance, the size of the space is the same as the source space
    vTarget.resize(v.size());
    transform(v.begin(), v.end(), vTarget.begin(), Transform());
    // Iterate over the target container
    for_each(vTarget.begin(), vTarget.end(), MyPrint());
}

int main(a)
{
    test01(a);return 0;
}
Copy the code

Note: the target container for handling must be opened up in advance, otherwise it cannot be handled normally