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?
I’m not sure I understood your code and your question well… but if you want a
std::mapassociatingstd::stringkeys tointvalues, why do you define an array of (key, value) pairs?What about the following, instead?
I think if you have an unordered array (like
opMapin 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 withstd::lower_bound()(which has logarithmic asymptotic complexity).If you want to initialize the map from the content of the
opMaparray, you can do something like this: