我想知道是否存在简化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();
}
}
}
答案 0 :(得分:6)
您可以使用std::map
/ std::unordered_map
来将函数映射到命令,而不是使用lambda来简化代码,然后可以使用基于范围的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]();
}
答案 1 :(得分:2)
我将添加一个函数来执行命令,然后从循环中调用它:
#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);
}
}