我可以使用lambda来简化for循环

1 c++ lambda for-loop functional-programming

我想知道是否有方法简化for循环,例如lambda表达式而不改变下面代码的性质.如果可能的话,我还想知道是否有其他方法(更好)执行一系列功能,可以像下面的代码那样做类似的事情.谢谢

#include <iostream>
#include <functional>
#include <vector>
using namespace std;
void turn_left(){  // left turn function
    cout<<"Turn left"<<endl;
}
void turn_right(){ // right turn function
    cout<<"Turn right"<<endl;
}
void onward(){  // moving forward function
    cout<<"Onward"<<endl;
}
int main() {
    vector<char>commands{'L', 'R', 'M'}; // commmands (keys)for robot to turn or move;
    vector<pair<function<void()>, char>> actions; // a vector of pairs, which pairs up the function pointers with the chars;
    actions.push_back(make_pair(turn_left, 'L')); //populate the vector actions
    actions.push_back(make_pair(turn_right, 'R'));
    actions.push_back(make_pair(onward, 'M'));
    for (int i =0; i<commands.size();++i){
        if(commands.at(i)==actions.at(i).second){
            actions.at(i).first();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Nat*_*ica 6

如果不使用lambda来简化代码,你可以使用的std::map/ std::unordered_map映射到的命令的功能,那么你可以简单地使用一个基于不等for循环它通过所有你的命令的迭代.

int main() {
    vector<char>commands{'L', 'R', 'M'}; // commmands (keys)for robot to turn or move;
    std::map<char, function<void()>> actions = {{'L', turn_left},{'R', turn_right},{'M', onward}};
    for (auto command : commands)
        actions[command]();
}
Run Code Online (Sandbox Code Playgroud)