Question

I have the following code:

//MyClass.h
class MyClass {
      typedef std::map<std::string, int> OpMap;
      static const OpMap::value_type opMap[OP_COUNT];

    public:
     //methods
};

//MyClass.cpp
const MyClass ::OpMap::value_type MyClass ::opMap[DDG::OP_COUNT] = {
    MyClass ::OpMap::value_type("hello", 42),
    MyClass ::OpMap::value_type("world", 88),
};

I need to implement function bool findOP(string opKey) which searches for opKey in the opMap.

Looks like I need to use a find method of the map class. But opMap.find(opKey) doesn't work, since opMap is an array of pairs. What is possible to do in order to search effectively for opKey in the opMap?

Was it helpful?

Solution

I'm not sure I understood your code and your question well... but if you want a std::map associating std::string keys to int values, why do you define an array of (key, value) pairs?

What about the following, instead?

std::map<std::string, int> m;
m["hello"] = 42;
m["world"] = 88;

I think if you have an unordered array (like opMap in your code), if you want to search something you can do a linear search (O(N)). Only if the array is sorted you can optimize the search using e.g. a binary search with std::lower_bound() (which has logarithmic asymptotic complexity).

If you want to initialize the map from the content of the opMap array, you can do something like this:

// opMap is an array of (key, value) pairs
// m is a std::map<std::string, int>
// 
// For each item in the array:
for (int i = 0; i < DDG::OP_COUNT; i++)
{
  // opMap[i].first is the key;
  // opMap[i].second is the value.
  // Add current key-value pair in the map.
  m[ opMap[i].first ] = opMap[i].second;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top