que*_*101 3 c++ iterator stl vector c++11
我正在尝试遍历存储在向量中的函数数组,并且我想通过迭代器指针对象调用它们中的每一个,但是类似这样:
itr->funcs[i](5); // call the ith index function && pass int 5 as param
Run Code Online (Sandbox Code Playgroud)
不是我猜的解决方案,那么解决方案是什么?
下面是我的代码,请检查代码中的最后一个 for 循环。
#include <iostream>
#include <string>
#include <vector>
// to be able to take other functions as arguments in a function
#include <functional>
using namespace std;
// receive other functions inside a function
// syntax: return_type function_name(std::function<return_type(parameter_lists)>func_name, parameter_lists)
double doMath(std::function<double(double)> someOtherFunction, double num){
return someOtherFunction(num);
}
double multBy2(double d){
// b'coz x is pointing to multBy2 the word 'someOtherFunction' in the
// above function behaves like an alias for this function 'multBy2'
return d * 2;
}
double multBy3(double d){
return d * 3;
}
int main (){
// dec && init
auto x = multBy2; // x pointing to multBy2 now
std::cout << "2 * 5.1 : " << x(5.1) << "\n";
std::cout << "multBy2 will be called: " << doMath(x, 6.1) << "\n";
std::cout << "multBy2 will be called, again: " << doMath(x, 6.1) << "\n";
// store different functions inside a vector
// you must use the same signature type functions
std::vector<function<double(double)>> funcs(2);
funcs[0] = multBy2; // multBy2 stored at the zeroth index
funcs[1] = multBy3; // multBy3 stored at the first index
// check
// funcs[0](10), pass value by index
std::cout << "2 * 10 = " << funcs[0](10) << "\n";
std::cout << "3 * 10 = " << funcs[1](10) << "\n";
// loop through them
for (auto itr = funcs.begin(); itr != funcs.end(); itr++){
// iterate through the functions
// itr->funcs[1](10); // I KNOW THIS IS WRONG, WHAT SHOULD I WRITE HERE?
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
变量itr是一个迭代器,它基本上是一个指针,即它们都指向一个对象。在这种情况下,迭代器指向一个函数。您可以通过使用 取消引用itr(很像指针)来访问该函数*itr。然后你可以像使用函数一样使用这个对象(因为它是一个):
for (auto itr = funcs.begin(); itr != funcs.end(); ++itr)
(*itr)(10); // like calling func[i](10)
Run Code Online (Sandbox Code Playgroud)
由于它是一个迭代器,您可能还想使用->运算符,以便您可以直接使用指向的对象。不幸的是,如果你试图做看起来很明显的事情:
itr->(10); // error
Run Code Online (Sandbox Code Playgroud)
该语言的语法不允许这样做(即使对于编译器,括号也很难弄清楚)。幸运的是,该语言确实有一种方法可以让您明确表达您的意思,即“我只是想把它当作一个函数,所以我可以用()”来调用它。有一个称为调用运算符的函数operator(),您可以使用它的拼写。其语法是:
for (auto itr = funcs.begin(); itr != funcs.end(); ++itr)
itr->operator()(10);
Run Code Online (Sandbox Code Playgroud)
然而,这种语法似乎首先违背了使用方便->运算符的目的。
但是,我建议您在这里使用 range-for 循环(如果可以使用它通常是更好的选择)。语法在表达代码的意图时更加清晰:
for (auto &func : funcs) // for every function in funcs
func(10); // use the function
Run Code Online (Sandbox Code Playgroud)
这是一个工作演示。
| 归档时间: |
|
| 查看次数: |
639 次 |
| 最近记录: |