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"
Solution: Use sprintf() function. You can also write your own function using ASCII values of numbers.
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.
To convert an integer to string in C#, use the ToString() method.
*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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With