对于C++17中的每个

这个 为了每个人 ()函数被添加到C++17技术规范中。它的思想借鉴了 地图 在里面 python 哈斯克尔 .此函数可以在有或没有 执行政策 .执行策略允许您决定是使用优化为在多个核上运行的新并行化功能,还是像以前的标准一样按顺序运行。甚至可以忽略执行策略,因为所有函数都有按顺序运行的重载对应项。

null

简单地说,对于_,each_n()有助于将公共函数应用于数组(或任何其他线性数据类型)的所有元素。它本质上是从给定迭代器开始批量更新一系列元素,并从该迭代器中更新固定数量的元素。

语法:

InputIt for_each_n( ExecutionPolicy&& policy,
           InputIt first, Size n, UnaryFunction f )

policy: [Optional] The execution policy to use.
The function is overloaded without its use.
first: The iterator to the first element 
you want to apply the operation on.
n: the number of elements to apply the function to.
f: the function object that is applied to the elements.  

(注意:给定的代码需要C++17或更高版本,可能无法在所有C++17环境中运行。)

// Requires C++17 or 17+
// C++ program to demonstrate the use for_each_n
// using function pointers as lambda expressions.
#include <bits/stdc++.h>
using namespace std;
/* Helper function to modify each element */
int add1( int x)
{
return (x + 2);
}
int main()
{
vector< int > arr({ 1, 2, 3, 4, 5, 6 });
// The initial vector
for ( auto i : arr)
cout << i << " " ;
cout << endl;
// Using function pointer as third parameter
for_each_n(arr.begin(), 2, add1);
// Print the modified vector
for ( auto i : arr)
cout << i << " " ;
cout << endl;
// Using lambda expression as third parameter
for_each_n(arr.begin() + 2, 2, []( auto & x) { x += 2; });
// Print the modified vector
for ( auto i : arr)
cout << i << " " ;
cout << endl;
return 0;
}


输出:

1 2 3 4 5 6
2 3 3 4 5 6
2 3 5 6 5 6

真正的力量和灵活性 为了每个人 ()只能通过使用 仿函数 作为第三个论点。

(注意:给定的代码需要c++17或更高版本,可能无法在所有c++17环境中运行。)

// Requires C++17 or 17+
// A C++ program to demonstrate the use for_each_n
// using funcctors.
#include <bits/stdc++.h>
using namespace std;
// A Functor
class add_del {
private :
int n;
public :
increment( int _n)
: n(_n)
{
}
// overloading () to create Functor objects
int operator()( int delta) const
{
return n + delta;
}
};
int main()
{
vector< int > arr({ 1, 2, 3, 4, 5, 6 });
// The initial vector
for ( auto i : arr)
cout << i << " " ;
cout << endl;
// Using functor as third parameter
for_each_n(arr.begin(), 2, add_del(1));
for_each_n(arr.begin() + 2, 2, add_del(2));
// Print the modified vector
for ( auto i : arr)
cout << i << " " ;
cout << endl;
return 0;
}


输出:

1 2 3 4 5 6
2 3 5 6 5 6
© 版权声明
THE END
喜欢就支持一下吧
点赞6 分享