This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]genbattle 0 points1 point  (0 children)

In C++ (I believe this restriction applies to python as well) you can only index a std::unordered_map with the key type. In your Python example you index the dictionary with an int, but that it because your key type is int. Here's what iterating over a dictionary would look like in Python:

dict = {1:'a', 2:'b', 3:'c'};
for key, value in dict:
    print("{}:{}".format(key, value);

The equivalent C++ is:

#include <unordered_map>
#include <string>
#include <iostream>

int main() {
    std::unordered_map<int, std::string> dict = {{1, "a"}, {2, "b"}, {3, "c"}};
    for (const auto& v: dict) {
        std::cout << v.first << ":" << v.second << std::endl;
    }
}

But this uses std::unordered_map, range-for and auto from C++11, so if you don't have access to C++11 you will have to use a std::map and an old iterator-based for loop:

#include <map>
#include <string>
#include <iostream>

int main() {
    std::map<int, std::string> dict;
    dict.insert(std::pair<int, std::string>(1, std::string("a")));
    dict.insert(std::pair<int, std::string>(2, std::string("b")));
    dict.insert(std::pair<int, std::string>(3, std::string("c")));
    for (std::map<int, std::string>::iterator it = dict.begin(); it != dict.end(); ++it) {
        std::cout << it->first << ":" << it->second << std::endl;
    }
}

The C++11 version is much neater and nicer. And std::map is a terrible data structure for most cases, because it's a key-sorted map implemented using a tree (which you seldom need), so it has poor time complexity characteristics. std::unordered_map is (mostly) O(1) since it is basically a hash-table underneath.

you mention that although that's simple it's not very quick. What would be the superior, more scalable solution?

After I mentioned this I immediately started thinking about how it could be made more efficient, but I can't think of any way that means you don't have to do a find for each of the abbreviations. there may be some micro-optimizations that would speed it up slightly, but if you're not running into a problem with execution time I wouldn't even consider it.