使用value_type的数组作为stl :: map [英] Using array of value_type for the stl::map

查看:277
本文介绍了使用value_type的数组作为stl :: map的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

//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),
};

我需要实现函数 bool findOP(string opKey) opMap 中搜索 opKey

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

看起来我需要使用 map 类的 find 方法。但是, opMap.find(opKey)不起作用,因为 opMap 是一对数组。为了在 opMap 中有效搜索 opKey 可以做什么?

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?

推荐答案

我不知道我理解你的代码和你的问题...但是如果你想要一个 std :: map 关联 std :: string 键到 int 值,为什么要定义一个数组(key ,价值)对?

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?

相反如何呢?

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

我想如果你有一个无序的数组(如 opMap 代码中),如果您想搜索可以进行线性搜索的( O( N))。只有当数组是排序时,您可以使用例如 $ std :: lower_bound()(具有对数渐近的复杂性)

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).

如果要从 opMap 数组的内容初始化地图,可以执行以下操作:

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

这篇关于使用value_type的数组作为stl :: map的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆