gpt4 book ai didi

C++ STL for_each 应该采用指向带有一个参数的成员函数的指针

转载 作者:太空狗 更新时间:2023-10-29 23:38:16 26 4
gpt4 key购买 nike

我必须将带有一个参数的成员 fn 的地址传递给 std::for_each。我该怎么做?

class A{

void load()
{
vector<int> vt(10,20);
std::for_each(vt.begin(), vt.end(), &A::print);
//It didnt work when i tried mem_fun1(&A::print)
}

void print(int a)
{
cout<<a;
}

};

谢谢

最佳答案

当使用 std::mem_fun 时,您必须将指针作为第一个参数传递给类。在这种情况下,您可以使用 std::bind1st 绑定(bind)它。

class A
{
public:
void print(int v) {std::cout << v;}

void load()
{
std::vector<int> vt(10, 20);

std::for_each(vt.begin(), vt.end(), std::bind1st(std::mem_fun(&A::print), this));
}
}

关于C++ STL for_each 应该采用指向带有一个参数的成员函数的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1678857/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com