for_each的便利之处非常明显,它遍历容器中的每个元素,并调用用户指定的函数,对每个元素进行处理。
现在的问题时,我想对处理函数在传入一个参数?
本次提供两种解决的方案,一种是使用利用bind1st(bind2nd类似)实现;另一种是通过类(结构体类似)构造实现,不过有两点需要注意一下:
1)使用bind1st函数时,目标函数需要使用ptr_fun函数适配;
2)使用类构造函数对象时,类要提供对应的仿函数operator ();
从本质上讲,这两种方法分别是以函数对象和类对象的方式传入for_each,至于为什么要这么做,感兴趣的可以看下for_each的源代码,代码举例如下:
void display(std::string str, int val)
{
std::cout << str.c_str() << val << std::endl;
}
class Test
{
public:
Test(std::string s) : str(s) {}
public:
void operator()(int val)
{
std::cout << str.c_str() << val << std::endl;
}
public:
std::string str;
};
int main(int argc, char* argv[])
{
std::vector<int> vec;
vec.push_back(1);
vec.push_back(2);
vec.push_back(3);
for_each(vec.begin(), vec.end(), Test("number = "));
for_each(vec.begin(), vec.end(), std::bind1st(ptr_fun(display), "value = "));
return 0;
}
分享到:
相关推荐
for_each遍历vector vector中可以是基本类型(int,double,char,string) 也可以是类类型
for_each 返回值实例详解;
STL算法(for_each/transform)
3.10. list_for_each_entry_reverse 13 3.10.1. 定义 13 3.10.2. 作用 13 3.11. list_for_each_entry_continue 13 3.11.1. 定义 13 3.11.2. 作用 13 3.11.3. 区别 13 3.12. list_for_each_safe_rcu 14 4. hlist...
对文件进行遍历,以行为单位进行输出,没一行构成一个列表元素,最终拼成一个列表。
各种机器学习方法的源代码,包括决策树、随机森林、神经网络等
for_each_practice 练习回购
matlab导入excel代码utl_calculate_mode_for_each_row 关键词:sas sql join合并大数据分析宏oracle teradata mysql sas社区stackoverflow statistics人工智慧AI Python R Java Javascript WPS Matlab SPSS Scala ...
C语言 计算机网络 发送ICMP_EACHO
改进了linux tailq队列下在遍历时删除多个元素的问题。可以使用TAILQ_FOREACH_SAFE下面进行节点删除操作。不会出现野指针问题
The implementation of numerical methods in MATLAB is integrated within each chapter and numerous examples in chemical engineering are provided, with a library of corresponding MATLAB programs....
1. 把矩阵向量相乘示例中的for_each(),for_each_n(),generate(),transform()等stl库函数调用改写成普通for循环。测试算例。 2. 保留上面的stl库函数调用,但添加execution的执行策略,测试并行的效果。 3. 调用...
Linux的list_for_each()? 这是来自知名来源的C代码的集合,当您想知道如何自己实现它时可以使用它们。 C源代码-信誉良好的参考 有时,我想知道我正在使用的某些C函数是如何实现的,例如,标准C库函数memmove() ...
In digital modulation techniques, a set of basis functions are chosen for a particular modulation scheme. Generally the basis functions are orthogonal to each other. Basis functions can be derived ...
Iterate a function on each entry of a directory for Linux.
Open vSwitch (OVS) allows Virtual Machines (VM) to communicate with each other and with the outside world. OVS traditionally resides in the hypervisor and switching is based on twelve tuple matching...
java 3d api for a cube with 3d dimension as we know it s most difficult to learn, so i have this code for help each other.
Segmentation of each particle in a frame across all frames in a video 跨视频中的所有帧分割一帧中的每个粒子 视频中跨所有帧的帧中每个粒子的分割 该脚本将读取视频文件并分割每一帧。 通过使用OTSU方法计算的...
Visual C#图片格式批量转换,可以在BMP/JPG/PNG/GIF四种格式之间任意转换
#define list_for_each_safe(head, pos, n) for(pos=head->next, n=pos->next; pos!=head; pos=n, n=n->next) node_t *request_link_list_node(void) { node_t *new_node; new_node = malloc(sizeof(node_t)); ...