gpt4 book ai didi

c++ - 简化 C++ if else 对于值范围的多个条件

转载 作者:太空狗 更新时间:2023-10-29 23:49:08 27 4
gpt4 key购买 nike

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

    if (x < 100 )
{
call_1();
}
else if (x < 500 )
{
call_2();
}
else
{
call_3();
}

是否有可用的标准库或结构,以便我可以映射范围和功能,无需接触条件语句即可扩展。?

最佳答案

您可以使用 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();
}

关于c++ - 简化 C++ if else 对于值范围的多个条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46120549/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com