Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

c

qt

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"
like image 735
yan bellavance Avatar asked Dec 15 '09 22:12

yan bellavance


People also ask

How can a number be converted to a String in C?

Solution: Use sprintf() function. You can also write your own function using ASCII values of numbers.

How do I map an int?

Solution Using Map To convert a list of strings to a list of integers, you can “map to int” by calling map(int, lst) on the int built-in function object as first and the lst object as second argument. The result is a map object that you can convert back to a list using the list() function.

How do I convert an int to a String in C#?

To convert an integer to string in C#, use the ToString() method.

Can we put String in map?

*You can Create map of both String and Integer, just keep sure that your key is Unique. I hope you find the above solution helpful.


2 Answers

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.

like image 53
R Samuel Klatchko Avatar answered Oct 13 '22 09:10

R Samuel Klatchko


Qt also provides it's own map implementations - QMap and QHash.

QMap<int, QString> myMap;
myMap[1234] = "Some value";
myMap[5678] = "Another value";

or

myMap.insert(1234, "Some value");

The documentation gives more examples but it's very easy to use.

like image 23
Rob Avatar answered Oct 13 '22 10:10

Rob