Call function from input C++ | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Call function from input C++

Hi, i have two public functions: set() & log(), i want to call a fuction when a specific variable is equal to the name of the function, but is there a more efficient way than: if (command == "set"){ set(); } If (command == "log"){ log(); }

7th Oct 2020, 10:43 AM
Cat Sauce
Cat Sauce - avatar
4 Answers
+ 3
♨️♨️ You can compare a C++ and a C style string.The C-style string will be implicitly converted to an std::string object before the comparison is done
7th Oct 2020, 11:21 AM
Anthony Maina
Anthony Maina - avatar
+ 2
It should be noted that == isn't going to work for you in every case. string overloads the operator to perform a compare, so == is the same as calling a compare. Alternatively, if you try this on objects that don't overload the == operator, you will be comparing their address in memory, and not their internal components. Calling compare is more safe. In the case of using std::string you are fine though. A major difference is that for comparing two strings size equality is checked before doing the compare and that makes the == operator faster than a compare.
7th Oct 2020, 11:24 AM
A S Raghuvanshi
A S Raghuvanshi - avatar
+ 2
I'm not sure you should be worried about performance for something like this because a few string comparisons to find which function to call that's reliant on user input will most likely be in the part of the program that's called very few times per second ( or even per minute ). Some things you could take into consideration are: - Use else if ( or a return inside the if ) instead of just ifs, because currently, if you find a match you'll still be checking other ifs unnecessarily. - Ordering. Put the most likely commands at the top of the if chain to save comparisons. - Use a map or an unordered_map to store string/function pointer pairs ( assuming each function has the same signature ) or to store string/id pairs. The id could be from an enum class. Integer comparisons are much faster than string comparisons which you could use with a switch. A switch usually uses a lookup table if you specify all integers without gaps between them or a binary search otherwise. But again, with just 2 commands, what you have now is fine.
7th Oct 2020, 11:58 AM
Dennis
Dennis - avatar
0
Dennis this was just a example i probably have like 30 commands
7th Oct 2020, 12:48 PM
Cat Sauce
Cat Sauce - avatar