首页 > 解决方案 > 我可以使用 lambda 来简化 for 循环吗

问题描述

我想知道是否有方法可以简化 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();
        }
    }
}

标签: c++for-looplambdafunctional-programming

解决方案


std::map您可以使用/将函数映射到命令,而不是使用 lambda 来简化代码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]();
}

推荐阅读