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

Can I use a lambda to simplify a for loop

本文关键字:for 循环 可以使 lambda 我可以      更新时间:2023-10-16

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

与其使用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]();
}

我会添加一个函数来执行命令,然后从循环中调用它:

#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;
}
// The next step is to put actions/executeAction() into a class.
vector<pair<char, function<void()>>> actions; // a vector of pairs, which pairs up the function pointers with the chars;
void executeAction(char command)
{
auto find = actions.find(command);
if (find != actions.end()) {
find->second();
}
}
int main() {
vector<char>commands{'L', 'R', 'M'}; // commmands (keys)for robot to turn or move;
actions.push_back(make_pair('L', turn_left)); //populate the vector actions
actions.push_back(make_pair('R', turn_right));
actions.push_back(make_pair('M', onward));
for (auto c: commands){
executeAction(c);
}
}