gpt4 book ai didi

c++ - std::for_each 和仿函数 - operator() 可以有哪些签名?

转载 作者:行者123 更新时间:2023-11-30 02:50:24 25 4
gpt4 key购买 nike

我想使用 std::for_each 调用来循环遍历一些值并调用仿函数将值映射到字符串,然后将该值返回给 for_each,像这样:

#include <iostream>
#include <map>
#include <string>
using std::string;
using std::map;
using std::cout;
using std::endl;

struct myfunctor
{
myfunctor(map<int, string>& x) : mymap(x) {
cout << "Inside myfunctor ctor" << endl;
};

map<int, string>& mymap;

string operator()(int mapthis)
{
cout << "Inside myfunctor operator(" << mapthis << ")" << endl;
return mymap[mapthis];
}
};

int main()
{
map<int, string> codes { {1, "abel"}, {2, "baker"}, {3, "charlie"} };

cout << "Main() - construct myfunctor" << endl;
myfunctor t(codes);

int arr[] = {1, 2, 3};

string blah;
cout << "Main() - begin for_each" << endl;
std::for_each(arr, arr+2, blah.append(t));
cout << blah << endl;
}

它无法编译,因为它无法将 myfunctor 转换为 string。但即使它这样做了,从 operator() 返回一些东西是否合法,以供 for_each 应用,就像我正在尝试做的那样?除了 for_each 的隐含范围变量之外,是否可以将其他参数传递给 operator()

如果 operator() 可以有返回值,我将如何编写一个 myfunctor 到字符串的转换方法?

除了void operator()(SingleArgument)

,我从未见过任何例子

最佳答案

首先,您必须将仿函数作为第三个参数传递给 std::for_each。您正在传递函数调用 blah.append(t) 的结果。此外,仿函数是应该在 for_each 期间完成所有工作的东西,因此您必须将调用转移到 appendoperator() 内部。最简单的方法:只需传递您的字符串作为引用。

struct myfunctor
{
myfunctor( string& toAppend, map<int, string>& x ) : appendage(toAppend), mymap( x ) {
cout << "Inside myfunctor ctor" << endl;
};

map<int, string>& mymap;
string& appendage;

void operator()(int mapthis)
{
cout << "Inside myfunctor operator(" << mapthis << ")" << endl;
appendage.append( mymap[mapthis] );
//std::for_each will not use a return value of this function for anything
}
};

void main2()
{
map<int, string> codes { {1, "abel"}, { 2, "baker" }, { 3, "charlie" } };

cout << "Main() - construct myfunctor" << endl;


int arr[] = { 1, 2, 3 };

string blah;
myfunctor t( blah, codes ); //Pass in blah so the functor can append to it.
cout << "Main() - begin for_each" << endl;
std::for_each( arr, arr + 3, t ); //arr+3 to loop over all 3 elems of arr
cout << blah << endl;
}

关于c++ - std::for_each 和仿函数 - operator() 可以有哪些签名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20484109/

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