【问题标题】:Most efficient way to access specific key of a map with an iterator?使用迭代器访问地图特定键的最有效方法?
【发布时间】:2014-07-21 08:26:31
【问题描述】:

我有一个std::map<std::string,int>,我想从它访问带有来自字符串值的迭代器的特定元素。我编写了以下代码。

map<string,int> mymap;
map<string,int>::iterator it=mymap.begin();

string find="Node";
        while( (it->first) !=find && it!= mymap.end())
               it++;

循环遍历地图的所有关键元素是最有效的方法吗?

【问题讨论】:

标签: c++ dictionary iterator key


【解决方案1】:

map 只是一个二叉搜索树。可以在O(log(N)) 时间找到给定的密钥。遍历整个列表需要O(N) 时间。

如果你想要一个迭代器,使用 map 的find 方法。如果您想引用数据,只需使用operator[]。这两个都将在O(log(N)) 时间运行。

【讨论】:

    【解决方案2】:
    map<string,int>::iterator it = mymap.find("Node");
    

    That's all.

    【讨论】:

    • 感谢您在我提供的示例代码上实现它的语法,我将把它作为答案,因为它会跟进示例并且可以在将来用作参考。跨度>
    【解决方案3】:

    为什么不直接使用地图的“查找”功能呢?

    【讨论】:

      【解决方案4】:

      如果要在地图上查找元素,请使用find 成员方法。 map 是针对此类操作优化的关联容器,无需遍历键。

      【讨论】:

        猜你喜欢
        • 2015-05-24
        • 2015-06-16
        • 2020-05-15
        • 1970-01-01
        • 2013-10-01
        • 2011-07-17
        • 2017-01-07
        • 2012-02-03
        • 2022-10-19
        相关资源
        最近更新 更多