如何创建查找表

时间:2014-04-14 14:41:23

标签: c++ class lookup-tables

基本上我只是意识到我编写项目的方式我需要实现某种形式的查找表,现在我从来没有这样做过,所以不知道怎么做,谷歌搜索没有真的给出了一套清晰的指示

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

4 个答案:

答案 0 :(得分:2)

你可以做这样的事情来创建一个查找(调度)表:

(注意:这是如何实现一个调度表,它是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;
}

(基于:Adding split-screen multiplayer to c++ game

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

答案 1 :(得分:1)

我不确切地知道你的要求,但我可以想象这样:

您可能需要查看C++ function pointers。你可以创建一个自己的结构:

  1. 功能名称
  2. 指向该功能的指针
  3. 变体的向量(例如来自boost或写下您的own)来保存参数
  4. 验证函数以查看参数和函数指针是否适合
  5. 为每个函数创建用户可以调用此结构的实例。显示给用户并让他选择。在第二步中,让他输入参数的值。

答案 2 :(得分:1)

您可以使用std::map<std::string, functype>其中functypetypedef'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);   
}

答案 3 :(得分:0)

我给你和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);
}
}

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