1. STL
Algorithm Overview
<algorithm>
<functional>
<numeric>
The algorithm is mainly contained in the header file<algorithm>
It is the largest of all STL header files and involves: traversal, comparison, search, exchange, copy, modification and other operations<functional>
Defines some template classes for declaring function objects<numeric>
Minimal, containing only a few template functions that perform simple mathematical operations on sequences
Algorithms are divided into: qualitative change algorithm and non-qualitative change algorithm
- Qualitative change algorithm : The content of the elements in the interval will be changed during the operation. For example, copy, replace, delete, etc.
- Non-qualitative algorithm : the content of elements in the interval will not be changed during the operation process, such as searching, counting, traversing, finding extreme values, etc.
2. for_each
Function: Traverse all elements in the container
for_each()
The algorithm is very flexible, allowing each element to be accessed, processed, and modified in different ways. Therefore,for_each()
it is both a qualitative change algorithm and a non-qualitative algorithm.
Function prototype: | for_each(iterator beg, iterator end, func) | explain |
---|---|---|
Parameter 1 | iterator beg | start iterator |
Parameter 2 | iterator end | end iterator |
Parameter 3 | func | function or function object |
accomplish:
//for_each()的实现如下
template <typename Iterator, typename Operation>
Operation for_each (Iterator beg, Iterator end, Operation op)
{
while(beg != end)
{
op(*beg);
++beg;
}
return op;
}
Example:
#include <iostream>
#include <algorithm> //必须包含该头文件
#include <vector>
using namespace std;
//普通函数
void printA(int value)
{
cout << value << " ";
}
//函数对象(仿函数)
class printB
{
public:
void operator()(int value)
{
cout << value << " ";
}
};
class printC
{
public:
void operator()(int& value)
{
value = value + 1; //修改入参的值
cout << value << " ";
}
};
void test01()
{
vector<int> vec;
for (int i = 0; i < 10; i++)
{
vec.push_back(i);
}
//普通函数遍历算法
cout << "for_each printA:";
for_each(vec.begin(), vec.end(), printA);
cout << endl;
//函数对象(仿函数)遍历算法-非质变算法
cout << "for_each printB():";
for_each(vec.begin(), vec.end(), printB());
cout << endl;
//函数对象(仿函数)遍历算法-质变算法
cout << "for_each printC():";
for_each(vec.begin(), vec.end(), printC());
cout << endl;
}
int main()
{
test01();
system("pause");
return 0;
}
//result
for_each printA:0 1 2 3 4 5 6 7 8 9
for_each printB():0 1 2 3 4 5 6 7 8 9
for_each printC():1 2 3 4 5 6 7 8 9 10
Note: Since C++11, range-based for循环
a more convenient and natural traversal method is provided. Therefore, for_each()
the importance of algorithms may gradually decrease.