C++ - 错误列表的数据结构

C++ - Data Structure for Error List

我有一个错误列表,如下所示:

"ERROR CODE" "POSITION" "Error description"
"000" "1" "No error"
"001" "2" "DB Connection error"
"002" "2" "Error in processing"

还有很多错误。

现在我真正需要做的是以某种方式实现这个错误(错误永远不会改变,它们总是一样的),以便使用该库的开发人员可以通过给定的 ERROR_CODE.

例如:char* getError(ERROR_CODE); return 与 ERROR_CODE.

关联的错误描述字符串

我想到了使用 ENUM。但我似乎无法让它正常工作。

如果错误代码是字符串,那么一种方法是使用 std::map<std::string, std::string>.

#include <map>
#include <string>
#include <iostream>

std::map<std::string, std::string> ErrCodeMap = 
   { {"000", "No error"}, 
     {"001", "DB Connection error"}, 
     {"002", "Error in processing"} };

std::string getError(const std::string& errCode)
{
   auto it = ErrCodeMap.find(errCode);
   if ( it != ErrCodeMap.end() )
      return it->second;
   return "";
}

int main()
{
   std::cout << getError("002") << "\n";
}

Live Example

如果错误代码的数据类型是 int,则将使用 std::map<int, std::string>

#include <map>
#include <string>
#include <iostream>

std::map<int, std::string> ErrCodeMap = 
   { {0, "No error"}, 
     {1, "DB Connection error"}, 
     {2, "Error in processing"} };

std::string getError(int errCode)
{
   auto it = ErrCodeMap.find(errCode);
   if ( it != ErrCodeMap.end() )
      return it->second;
   return "";
}

int main()
{
   std::cout << getError(2) << "\n";
}

Live Example using int

我认为标准模板库的 class 模板 unordered_map or map 将适合您的目的。

无序映射是关联容器,存储由键值和映射值组合而成的元素,键值一般用于唯一标识元素,而映射值是一个对象,其内容关联到这把钥匙。无序映射中的元素未根据其键或映射值按任何特定顺序排序。

Map是关联容器,存储由键值和映射值组合而成的元素,键值一般用于对元素进行排序和唯一标识,而映射值存储与该键关联的内容.在内部,映射中的元素始终按其键排序。

无序地图容器比地图容器更快地通过键访问单个元素,尽管它们通过其元素的子集进行范围迭代的效率通常较低。

将错误代码存储为键,并将包含位置和错误描述的结构(如下所示)存储为映射值。

struct error_info{
    int position;
    char * description;
};

已编辑:

这是代码,

#include <iostream>
#include <map>
using namespace std;

struct error_info{
    int position;
    char * description;
};

struct error_info get_error(map<int, struct error_info> error_map, int error_code){
    return error_map[error_code];   
}

int main(){
    map<int, struct error_info> error_map;

    error_map[000] = {1, (char *)"no error"};
    error_map[001] = {2, (char *)"DB connection error"};
    error_map[003] = {3, (char *)"error in processing"};

    struct error_info info = get_error(error_map, 001);
    cout << info.position << " " << info.description << endl;
    return 0;
}

Live example

希望对您有所帮助。