【问题标题】:Using array of value_type for the stl::map为 stl::map 使用 value_type 数组
【发布时间】:2012-11-07 23:11:55
【问题描述】:

我有以下代码:

//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

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

【问题讨论】:

    标签: c++ arrays map find value-type


    【解决方案1】:

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

    那么下面的呢?

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

    我认为如果您有一个 无序 数组(例如 您的 代码中的 opMap),如果您想搜索某些内容,您可以进行 线性搜索 (O(N))。只有当数组是 sorted 时,您才能使用例如优化搜索。带有std::lower_bound()(具有对数渐近复杂度)的二分搜索

    如果你想从opMap数组的内容初始化地图,你可以这样做:

    // 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 进行静态“地图初始化”,但我仍然想使用 orer 中的地图属性来进行有效的搜索(查找)
    • @Yakov:我添加了一个示例代码来根据数组的内容初始化映射:只需遍历数组,并在映射中添加每个键值对。
    • 我不想从数组中初始化地图。我只是认为由于数组是从地图“构建”的,因此可以简单地将数组转换为地图
    • @Yakov:如果你想使用“地图属性”(如你所写),你必须用一些数据填充地图。你有一个键值对数组,但它只是一个数组。如果要使用std::map 成员函数,则必须将此数据放入映射中。
    • @Yakov 如果你有可用的 C++11,你可以直接初始化一个地图。在 C++03 中,您可以使用 boost::assign,有关更多信息,请参阅 stackoverflow.com/q/2172053/1030301
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-30
    • 2019-04-25
    相关资源
    最近更新 更多