go4sri
go4sri

Reputation: 1490

Error Id to Error String mapping - implementation in C++

I am implementing a class that will handle the error messages for my application. The primary requirement for this class will be

  1. Store the error id to string mapping( during compile time)

    0, "No Error"

    147, "Invalid Input"

    . . .

    2500, "Unknown error"

  2. A method const std::string& getErrorString(int errorId) that will retrieve the string from the mapping

The errorIds are not contiguous, because I am going to assign ranges for modules. I was considering using a map to store the mapping, but this would mean that I would have to insert the error strings into the map at run-time - I am not sure if this is efficient, as all errors are available during compilation itself.

What is the best way to implement the error id to string mapping to allow for efficient retrieval and optimal run time? I do not have boost.

Upvotes: 1

Views: 452

Answers (2)

Michael Krelin - hacker
Michael Krelin - hacker

Reputation: 143061

Depending on how many of them you have and how often you call the function, it may be easier to just have an array of structs with ints and const char *s and scan through it. Alternatively, you may split this array into ranges, though whether the performance gain worth the maintenance effort is up to you to determine.

Upvotes: 0

Kerrek SB
Kerrek SB

Reputation: 476970

The dynamic initialization phase of your program startup is the ideal place for this:

std::map<int, std::string> const Errors {
  { 0, "No Error" },
  { 1, "Bad mojo" },
  /* ... */
  { 2500, "Unknown error" },
};

std::string const & getErrorString(int errorId)
{
    auto it = Errors.find(errorId);
    return it != Errors.end() ? it->second : Errors.find(2500)->second;
}

Upvotes: 1

Related Questions