how can I map an int to a corresponding string in C/C++

c c++ qt

Question

I have 20 digits and I would like to associate them with strings. Is there a faster way besides using a switch case statement to achieve this.

I need to convert an int to a corresponding string and the numbers aren't necessarily packed. Some code in Qt as well might be useful?

Example: The following digits and strings are associated with each other,

1:   "Request System Info"

2:   "Change System Info"

10:  "Unkown Error"
1
4
4/16/2013 1:30:48 PM

Accepted Answer

easier way to use map

std::map<int, std::string> mymap;
mymap[1] = "foo";
mymap[10] = "bar";
// ...
int idx = 10;
std::string lookup = mymap[idx];
5
11/6/2015 10:11:56 PM

I recommend std::map<>

#include <map>
#include <string>

std::map<int, std::string> mapping;

// Initialize the map
mapping.insert(std::make_pair(1, "Request System Info"));
mapping.insert(std::make_pair(2, "Change System Info"));
mapping.insert(std::make_pair(10, "Unkown Error"));

// Use the map
std::map<int, std::string>::const_iterator iter =
    mapping.find(num);
if (iter != mapping.end())
{
    // iter->second contains your string
    // iter->first contains the number you just looked up
}

If you have a compiler that implements the initalizer-list feature of the draft C++0x standard, you combine your definition and initialization of the map:

std::map<int, std::string> mapping = {{1, "Request System Info"},
                                      {2, "Change System Info"}
                                      {10, "Unkown Error"}};

std::map<> scales well to a large number of entries as std::map<>::find runs in O(log N). Once you have the hash-map feature of the draft C++0x standard, you can easily convert this to a std::unordered_map<> which should be able to look things up in O(1) time.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon