How to fill vector with values returned by a member function in C++03?
我希望得到与此相同的行为:
1 2 3 | IdentifiersGenerator gen; for(int i = 0; i < 100; ++i) v.push_back(gen.getNextIdentifiers()); |
具有类似于以下内容的语法:
1 2 3 4 | IdentifiersGenerator gen; std::vector<Identifiers> v(100); std::generate(v.begin(), v.end(), std::bind1st(std::mem_fun(&IdentifiersGenerator::getNextIdentifiers), gen)); |
以上代码段给出以下错误:
1 2 3 4 5 6 7 8 9 | test/src/IdentifiersGeneratorTest.cpp:449: instantiated from here /usr/lib/gcc/x86_64-redhat-linux/4.4.6/../../../../include/c++/4.4.6/backward/binders.h:100: error: no type named a€?second_argument_typea€? in a€?class std::mem_fun_t<const Identifiers&, IdentifiersGenerator>a€? /usr/lib/gcc/x86_64-redhat-linux/4.4.6/../../../../include/c++/4.4.6/backward/binders.h:103: error: no type named a€?first_argument_typea€? in a€?class std::mem_fun_t<const Identifiers&, IdentifiersGenerator>a€? /usr/lib/gcc/x86_64-redhat-linux/4.4.6/../../../../include/c++/4.4.6/backward/binders.h:106: error: no type named a€?first_argument_typea€? in a€?class std::mem_fun_t<const Identifiers&, IdentifiersGenerator>a€? /usr/lib/gcc/x86_64-redhat-linux/4.4.6/../../../../include/c++/4.4.6/backward/binders.h:111: error: no type named a€?second_argument_typea€? in a€?class std::mem_fun_t<const Identifiers&, IdentifiersGenerator>a€? /usr/lib/gcc/x86_64-redhat-linux/4.4.6/../../../../include/c++/4.4.6/backward/binders.h:117: error: no type named a€?second_argument_typea€? in a€?class std::mem_fun_t<const Identifiers&, IdentifiersGenerator>a€? /usr/lib/gcc/x86_64-redhat-linux/4.4.6/../../../../include/c++/4.4.6/backward/binders.h: In function a€?std::binder1st<_Operation> std::bind1st(const _Operation&, const _Tp&) [with _Operation = std::mem_fun_t<const Identifiers&, IdentifiersGenerator>, _Tp = IdentifiersGenerator]a€?: test/src/IdentifiersGeneratorTest.cpp:449: instantiated from here /usr/lib/gcc/x86_64-redhat-linux/4.4.6/../../../../include/c++/4.4.6/backward/binders.h:126: error: no type named a€?first_argument_typea€? in a€?class std::mem_fun_t<const Identifiers&, IdentifiersGenerator>a€? |
也许即使没有
编辑OK,所以我意识到我可以像这样使用
1 2 3 | std::vector<AlarmIdentifiers> v(100); std::generate(v.begin(), v.end(), boost::bind(&IdentifiersGenerator::getNextIdentifiers, &gen)); |
任何人都可以共享一种使用指向成员函数的指针初始化向量的方法,而不是构造并在内部生成向量吗?
不起作用的原因:
1 | std::bind1st(std::mem_fun(&IdentifiersGenerator::getNextIdentifiers), gen) |
是
否则,可以编写自己的工厂,该工厂将使用一个指向null成员函数的指针和一个指向该类的指针,并返回带有
bind实际上是实现与更好的lambda语法相似的东西的一种"古老"且几乎过时的方法。
1 2 3 | IdentifiersGenerator gen; std::vector<Identifiers> v(100); std::generate(v.begin(), v.end(), [&](){ return gen.getNextIdentifiers(); }); |
您也可以使用generate_n
(仅在此处发布以供参考)
好,所以我意识到我可以像这样使用
1 2 3 | std::vector<AlarmIdentifiers> v(100); std::generate(v.begin(), v.end(), boost::bind(&IdentifiersGenerator::getNextIdentifiers, &gen)); |