我可以使用 lambda 来简化 for 循环吗?
Can I use a lambda to simplify a for loop
我想知道是否有方法可以简化 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);
}
}
相关文章:
- 如何在C++中从两个单独的for循环中添加两个数组
- 为什么我的for循环不能正确获取argv
- 在基于范围的for循环中使用结构化绑定声明
- 通过for循环使用用户输入填充列表
- 使用for循环检查数组中的重复项
- 在for循环中使用auto vs decltype(vec.size())来处理字符串的向量
- 为什么 const std::p air<K,V>& 在 std::map 上基于范围的 for 循环不起作用?
- 正在使用for循环创建QScatterSerie
- Python中的for循环与C++有何不同
- 在更改for循环的第三部分后,未使用for循环结果
- 在 for 循环中查找问题时遇到困难
- 嵌套for循环C++的问题(初学者)
- 如何用for循环在c++中生成单词三角形
- 如何在for循环中包含两个索引值的测试条件
- 带有多个独立参数的C++For循环
- 为什么我的程序在for循环中k=0时返回垃圾值
- 如何通过替换顺序代码的while循环来添加OpenMP for循环
- C++-For循环未执行
- 基于范围的 for 循环:迭代使用一个元素扩展的向量
- C++ 无法在字符数组中使用 for 循环打印字母模式