【发布时间】:2023-03-29 08:27:01
【问题描述】:
我想使用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-to-string的转换方法?
我从未见过除void operator()(SingleArgument)以外的任何例子
【问题讨论】: