C++17 std::for_each/for_each_n

std::for_each/for_each_n

1.1.std::for_each(iterator,iterator,callback);/std::for_each(iterator,n,callback);
      参数1,2容器迭代器
      参参数3是回调函数-必须满足可复制构造 (CopyConstructible) 的要求
1.2.回调函数的原理都是将参数传递至相应的函数体,再进行操作

2.实例1:
#include 
#include 
#include 

int main(){
 std::vector vec{ 1, 2, 3, 4, 5 };
 for (auto n : vec) std::cout << n << ", ";//1, 2, 3, 4, 5,
 std::cout << '\n';
 std::for_each_n(vec.begin(), 3, [](auto& n) { n += 10; });
 for (auto n : vec) std::cout << n << ", ";//11, 12, 13, 4, 5,
 std::cout << '\n';
}

实例2:
#include 
#include 
#include 
#include 
#include 
#include 
using namespace std;
struct Sum{
 Sum() : sum{ 0 } { }
 void operator()(int n) { sum += n; }
 int sum;
};

int main(){
 int arr[] = { 1,2,3,4,5 };
 std::vector vec = { 11,12,13,14,15 };
 std::initializer_list lst = { 21,22,23,24,25 };
 std::map dict = { {"Tom",10},{"Bob",20} };
 
 for_each(begin(arr), end(arr), [](int i)->void {cout << i << endl; });
 for_each(begin(vec), end(vec), [](int i)->void {cout << i << endl; });
 for_each(begin(lst), end(lst), [](int i)->void {cout << i << endl; });
 for_each(begin(dict), end(dict), [](std::pair ele)->void {cout << ele.first .c_str()<< ele.second << endl; });

 auto print = [](const int& n) { cout << n << endl;; };
 for_each(vec.begin(), vec.end(), print);

 for_each(vec.begin(), vec.end(), [](int &n) { n++; });//元素+1
 for_each(vec.begin(), vec.end(), print);

 Sum s = std::for_each(vec.begin(), vec.end(), Sum());// 对每个数调用 Sum::operator()
 cout << "sum: " << s.sum << '\n';
}

 

你可能感兴趣的:(C/C++)