【问题标题】:Iterating over a map, starting at a specific key从特定键开始迭代地图
【发布时间】:2020-05-15 16:02:32
【问题描述】:

我正在实现一个函数,该函数旨在查找与给定字符串共享前缀的任何字符串。要比较的所有可能的字符串都已经在映射中,我想从给定字符串所在的位置开始迭代该映射。目前,我正在循环整个地图,但出于性能原因,我需要提高效率。这就是我目前在地图上迭代的方式:

for(auto const& it : lookup_map){ //performs code }

我希望这不是从地图的开头开始,而是从地图中给定字符串的任何位置开始。

【问题讨论】:

    标签: c++ loops dictionary iterator stdmap


    【解决方案1】:

    只需使用好的旧迭代器:

    for( auto it = lookup_map.find( your_string ); it != lookup_map.end(); ++it ) {
       // using it
    }
    

    【讨论】:

    • 这可能需要lower_bound 而不是find
    【解决方案2】:

    std::map 有它自己的成员函数 lower_bound 来做你想做的事。您可以使用std::map::lower_bound 获取您的起始位置,然后比较前缀以进行后续迭代:

    for (auto it = lookup_map.lower_bound(prefix);
        it != std::end(lookup_map) && it->first.compare(0, prefix.size(), prefix) == 0;
        ++it)
    {
        ...
    }
    

    这将比迭代每个键更有效。在这种情况下使用lower_bound() 的优点是它将返回等效或搜索词之后的第一个项目。因此,如果您的搜索词是“aa”并且您的地图中有一个条目“aab”,lower_bound() 将返回一个迭代器到“aab”。我认为这在您的情况下会更有用,因为您想搜索前缀。


    在 C++20 中,std::string 有一个 starts_with() 函数。所以我们可以使用这个函数来检查前缀并稍微简化我们的代码:

    for (auto it = lookup_map.lower_bound(prefix);
         it != lookup_map.end() && it->first.starts_with(prefix); ++it)
    {
        ...
    }
    

    Demo

    【讨论】:

      猜你喜欢
      • 2018-08-17
      • 1970-01-01
      • 2023-01-23
      • 2014-01-15
      • 1970-01-01
      • 1970-01-01
      • 2017-11-13
      • 2021-08-02
      • 1970-01-01
      相关资源
      最近更新 更多