c++ - 我可以使用 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();
}
}
}
解决方案
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]();
}
推荐阅读
- java - 在流结束之前调用 MediaPlayer.onCompletion()?
- javascript - 使用节点 js / javascript 从数组中获取第一个元素
- django - 为什么外键项没有连接?
- html - 如何编辑两个ID?
- reactjs - 如果 SSR 不是目标,是否最好将 Next.js 与 ASP.NET Core Web api 一起使用?
- html - humburber 菜单不显示在网络上
- sql - 使用 SQL 计算组/分区的累积百分位数
- css - 当浏览器窗口调整大小时,二维网格节点重叠
- hadoop - 压缩/解压缩,是什么使编解码器可拆分?
- time-series - 如何为 LSTM 重塑数据 - 时间序列多类分类