std::for_each和functors-运算符()可以有什么签名

std::for_each and functors - what signatures can operator() have?

本文关键字:什么 运算符 for each std functors-      更新时间:2023-10-16

我想使用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到字符串的转换方法?

I;除了void operator()(SingleArgument) ,我从未见过其他任何东西的例子

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

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;
}