simpliyfy C++ if else for values for values of values

pra*_*sad 2 c++ if-statement std

我有多个C++ if else条件用于检查某个变量的范围和调用具有相同签名的函数

    if (x < 100 )
{
 call_1();
}
else if (x < 500 )
{
call_2();
}
else 
{
call_3();
}
Run Code Online (Sandbox Code Playgroud)

是否有任何标准库或结构可供使用,以便我可以映射范围和功能,可以扩展而无需触及条件语句.

Kan*_*ane 8

您可以使用std::map存储指向函数的指针.然后你可以std::map::lower_bound()用来找到一个正确的功能.

这是一个小例子:

#include <map>
#include <limits>

void call_1() {}
void call_2() {}
void call_3() {}

std::map<int, void(*)()> functions = {
    { 99, &call_1 },
    { 499, &call_2 },
    { std::numeric_limits<int>::max(), &call_3 }
};

void call(int x)
{
    functions.lower_bound(x)->second();
}
Run Code Online (Sandbox Code Playgroud)