C++ 如何创建查找表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23063074/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 00:18:24  来源:igfitidea点击:

How to create a lookup table

c++classlookup-tables

提问by Tomsta

Basically i've only realised that the way i've coded my project i need to implement some form of lookup table, now i have never done this before and therefore don't know how to do it and googling doesn't really give a clear set of instructions

基本上我只意识到我编码我的项目的方式我需要实现某种形式的查找表,现在我以前从未这样做过,因此不知道如何去做,谷歌搜索并没有真正给出清晰的指令集

I need the lookup table so that a user can input a function into the command line and then pass in parameters to that function, but no idea where to start

我需要查找表,以便用户可以在命令行中输入一个函数,然后将参数传递给该函数,但不知道从哪里开始

回答by Nick Louloudakis

You could do something like this in order to create a lookup (dispatch) table:

您可以执行以下操作以创建查找(调度)表:

(Notice: This is how to implement a dispatch table and it is both C and C++ compartible. There are other-and maybe easier ways to do this in C++ without reinventing the wheel, like using some containers etc).

(注意:这是实现调度表的方法,它是 C 和 C++ 兼容的。在 C++ 中还有其他更简单的方法可以做到这一点,而无需重新发明轮子,例如使用一些容器等)。

#include <iostream>

using namespace std;

// Arrays start from 0.
// This is used for code
// readability reasons.
#define CASE(X) X-1 

typedef void (*chooseCase)();

// Functions to execute each case.
// Here, I am just printing
// different strings.
void case1(){
    cout<< "case1" << endl;
}

void case2(){
    cout<< "case2" << endl;
}

void case3(){
    cout<< "case3" << endl;
}

void case4(){
    cout<< "case4" << endl;
}

//Put all the cases in an array.
chooseCase cases[] = {
    case1, case2, case3, case4
};

int main()
{
    //You can call each scenario
    //by hand easily this way:
    cases[CASE(1)]();
    cout << endl;

    //Idea: You can even set in another
    // array a sequence of function executions desired.
    int casesSequence[] = {
        CASE(1), CASE(2), CASE(3), CASE(4),CASE(3),CASE(2),CASE(1)
    };
    //Execute the functions in the sequence set.
    for(int i = 0; i < (sizeof(casesSequence)/sizeof(int)); ++i){
        cases[casesSequence[i]]();
    }

    return 0;
}

(Based on: Adding split-screen multiplayer to c++ game)

(基于:将分屏多人游戏添加到 c++ 游戏

Now about the program input, you could map the name of your function to get the index for example and you could apply the example above to parameterized functions and you can also use this in situations that functions are parameterized. In this case,please take into consideration that all functions should obey to the function pointer signature in order to use it in this example. Otherwise, you have to do more tricky things (like using a void* argument and passing an arguments struct"instance" pointer to each function).

现在关于程序输入,您可以映射函数的名称以获取例如索引,您可以将上面的示例应用于参数化函数,您也可以在函数被参数化的情况下使用它。在这种情况下,请考虑到所有函数都应遵守函数指针签名,以便在本示例中使用它。否则,您必须做更多棘手的事情(例如使用void* 参数并将参数struct“实例”指针传递给每个函数)。

回答by Brian Cain

You can use std::map<std::string, functype>where functypeis a typedef'd function pointer, or even a boost::function<>type.

您可以使用std::map<std::string, functype>wherefunctype是一个typedef'd 函数指针,甚至是一个boost::function<>类型。

std::map<std::string, functype> funcs;

void call_user_func(const std::string &user_input, const std::string &arg1, const std::string & arg2)
{
    functype f = funcs.at(user_input);
    f(arg1, arg2);   
}

回答by CppChris

I don't know exactly your requirements, but I could imagine sth like this:

我不确切知道您的要求,但我可以想象这样的事情:

You might want to have a look into C++ function pointers. You could make an own struct that holds:

你可能想看看C++ function pointers。您可以创建一个自己的结构,其中包含:

  1. name of a function
  2. pointer to that function
  3. vector of variants (for example from boostor write yourown) to hold the arguments
  4. validate function to see if the arguments and function pointer fit
  1. 函数名
  2. 指向该函数的指针
  3. 变量向量(例如来自boost或编写自己的)来保存参数
  4. 验证函数以查看参数和函数指针是否合适

Create for each function that the user can call a an instance of this struct. Display those to the user and let him choose. In the second step, let him enter the values for the arguments.

为用户可以调用的每个函数创建一个此结构的实例。将这些显示给用户并让他选择。在第二步中,让他输入参数的值。

回答by Rafalenfs

I give you and example on Arduino that is almost the same C/C++ code analogy

我给你和 Arduino 的例子,这几乎是相同的 C/C++ 代码类比

float cosLUT[(int) (360.0 * 1 / 0.5)] ;
const float DEG2RAD = 180 / PI ;
const float cosinePrecision = 0.5;
const int cosinePeriod = (int) (360.0 * 1 / cosinePrecision);
void setup()
{
initCosineLUT();
}
void loop()
{
// nothing for now!
}
void initCosineLUT(){
for (int i = 0 ; i < cosinePeriod ; i++)
{
cosLUT[i] = (float) cos(i * DEG2RAD * cosinePrecision);
}
}

Lookup tables are one of the most powerful tricks in the programming universe. They are arrays containing precalculated values and thus replace heavy runtime calculations by a simpler array index operation. For instance, imagine you want to track positions of something by reading distances coming from a bunch of distance sensors. You'll have trigonometric and probably power calculations to perform. Because they can be time consuming for your processor, it would be smarter and cheaper to use array content reading instead of those calculations. This is the usual illustration for the use of lookup tables.

查找表是编程领域中最强大的技巧之一。它们是包含预先计算值的数组,因此用更简单的数组索引操作代替了繁重的运行时计算。例如,假设您想通过读取来自一堆距离传感器的距离来跟踪某物的位置。您将需要执行三角函数和可能的幂计算。因为它们对您的处理器来说可能很耗时,所以使用数组内容读取而不是那些计算会更智能、更便宜。这是使用查找表的常用说明。