简体   繁体   English

使用C ++中的函数指针映射枚举键和值

[英]Map enum key and value using function pointer in C++

i am very new to C++ programming. 我对C ++编程非常陌生。 I am doing my master and working on one problem given by professor. 我正在做我的硕士,正在研究教授给出的一个问题。 the problem is regarding performing the basic operations on binary search tree. 问题是关于在二叉搜索树上执行基本操作。 i have one file which has below format : 我有一个文件,其格式如下:

I 1015291402
I 729831403
I 1005116371
F 757970570
D 1005116371
F 729831403
I 1218751282
D 1015291402
I 582339464
I 92421221

There are three basic operations Insert, Delete and Find can be done on search tree. 可以在搜索树上完成三种基本操作:插入,删除和查找。 so i need to read this file perform operation line by line. 所以我需要逐行读取该文件进行操作。 Below is the code i wrote so far. 以下是我到目前为止编写的代码。

string line;
ifstream infilesmall("inputfile_small.txt");
//ifstream infilelarge("inputfile_small.txt");

while (getline(infilesmall, line))
{
    istringstream iss(line);
    vector<string> tokens;
    copy(istream_iterator<string>(iss), istream_iterator<string>(), back_inserter(tokens));
    string  str = ((tokens)._Myfirst)[0];
    cout<< ((tokens)._Myfirst)[1];

    //char operation =  new char(((tokens)._Myfirst)[0]);
    /*typedef void (*funcPointer)(int);
    void String1Action(int arg);
    void String2Action(int arg);
    map<string, funcPointer> stringFunctionMap;
    stringFunctionMap.add("string1", &String1Action);*/

    insert(t,10);
    find(t,0);
    //Delete(t,10);
}

so the question what is ideal way of calling Insert, Delete and Find by splitting the line? 因此,问题是通过拆分行来调用“插入”,“删除”和“查找”的理想方式是什么? i need to take care the performance. 我需要照顾好表演。 One approach i found out is to create enum with key and value pair and having function pointer. 我发现的一种方法是创建具有键和值对并具有函数指针的枚举。 so depending on the key value ("I","D","F") the appropriate function will be called with it's respective value. 因此根据键值(“ I”,“ D”,“ F”),将使用其各自的值来调用适当的函数。 Can you please suggest me/correct my approach and guide me on this code. 您能否建议我/更正我的方法并指导我使用此代码。 Appreciate your time. 感谢您的时间。 Thanks 谢谢

Your code is needlessly complex. 您的代码不必要地复杂。 You can read the operator and the number from the file, one pair at a time, and use the number appropriately based the value of the operator. 您可以一次从文件中读取运算符和数字,然后根据运算符的值适当地使用数字。

char op;
int number;
while ( infilesmall >> op >> number )
{
   switch (op)
   {
      case 'I':
         insertData(number);
         break;

      case 'D':
         deleteData(number);
         break;

      case 'F':
         findData(number);
         break;

      default:
         std::err << "Unknown operator, " << op << std::endl;
   }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM