I have an error list that looks like:
"ERROR CODE" "POSITION" "Error description"
"000" "1" "No error"
"001" "2" "DB Connection error"
"002" "2" "Error in processing"
and a lot more errors.
Now what i really need to do is to implement this errors (errors never change, they are always the same) somehow so that the developers that use the library can easily identify the error description by the given ERROR_CODE.
eg: char* getError(ERROR_CODE); and to return the string of the error description associated to ERROR_CODE.
I thought of using ENUM. But i can't seem to make it work properly.
I think the Standard Template Library's class template unordered_map or map will suit your purpose.
Unordered maps are associative containers that store elements formed by the combination of a key value and a mapped value, the key value is generally used to uniquely identify the element, while the mapped value is an object with the content associated to this key. The elements in the unordered map are not sorted in any particular order with respect to either their key or mapped values.
Maps are associative containers that store elements formed by a combination of a key value and a mapped value, the key values are generally used to sort and uniquely identify the elements, while the mapped values store the content associated to this key. Internally, the elements in a map are always sorted by its key.
unordered map containers are faster than map containers to access individual elements by their key, although they are generally less efficient for range iteration through a subset of their elements.
Store your error code as key and a structure(like one below) containing position and error description as your mapped value.
struct error_info{
int position;
char * description;
};
Here's the code,
#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;
}
Hope this will help you.