Using array of value_type for the stl::map

送分小仙女□ 提交于 2019-12-13 06:28:34

问题


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?


回答1:


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;
}


来源:https://stackoverflow.com/questions/13463825/using-array-of-value-type-for-the-stlmap

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!