std::for_each和functors-运算符()可以有什么签名
std::for_each and functors - what signatures can operator() have?
我想使用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;
}
相关文章:
- 重载运算符的范围是什么?它是否会影响作为类成员的集合的插入函数?
- 如果我真的真的想从 STL 容器继承,并且我继承构造函数并删除新运算符,会发生什么?
- 这里的 = 运算符有什么用法?
- unique_ptr < 0 或小于运算符做什么?
- "operator()"在重载运算符方法中是什么意思,在priority_queue(STL)中用作C++中的比较器?
- 是什么让一些命名函数/运算符与众不同?
- C++,()运算符重载,它的工作是什么
- 提供运算符+或运算符到双向迭代器有什么缺点吗?
- std::set<Key,Compare,Allocator>::find() 函数使用"<"运算符而不是"=="运算符背后的直觉是什么?
- 有什么理由不扩展 std::set 以添加下标运算符吗?
- 在C++中,运算符 sizeof 返回什么数据类型?
- 运算符++();调用和++(*this)有什么区别?
- 第二个常量在运算符函数中做什么?
- 使输出流式处理运算符适用于 boost::variant<std::vector<int>、int、double 的正确方法是什么>
- 当值传递给C++中的运算符重载函数时会发生什么
- 除了调用全局删除运算符之外,删除一个void指针还能做什么呢
- 在复制构造函数中放入什么 = 运算符重载
- 什么C++运算符在这里被重载了
- 当类作为参数传递给printf()时,要重载什么运算符
- 如果我想使用什么运算符" a = {x, y};"