简体   繁体   中英

Can I use a lambda to simplify a for loop

I would like to know if there are ways to simplify the for loop, such as a lambda expression without changing the nature of the code below. If possible, I would also like to know if there are other ways(better) to execute a series of functions that could do something similarly like the code below. Thank you

#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();
        }
    }
}

Instead of using a lambda to make the code simpler you can use a std::map / std::unordered_map to map a function to a command and then you can simply use a ranged based for loop it iterate through all of the commands you have.

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]();
}

I would add a function to execute a command then call that from the loop:

#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);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM