【问题标题】:Is there a way to convert local_iterator to const_iterator or iterator?有没有办法将 local_iterator 转换为 const_iterator 或迭代器?
【发布时间】:2021-10-22 23:45:13
【问题描述】:

我们如何将 unordered_multimap::local_iterator 更改为 unordered_multimap::iterator 或 unordered_multimap::const_iterator? 我需要更改,因为我们无法使用 local_iterator 擦除元素,而擦除只能使用 iterator/const_iterator 来完成。如果有其他使用 local_iterator 擦除的方法,请提出建议。

【问题讨论】:

标签: c++ iterator unordered-map unordered-multimap


【解决方案1】:

有点费力,但您可以遍历 equal_range() 的结果,直到找到正确的迭代器:

template<typename Cont>
typename Cont::iterator local_to_regular_iterator(Cont& c, typename Cont::local_iterator local_ite) {
  auto range = c.equal_range(local_ite->first);

  for(auto ite = range.first; ite != range.second; ++ite) {
    if(&ite->second == &local_ite->second) {
      return ite;
    }
  }

  throw std::out_of_range("huh?");
}

据我所知,这是你目前所能得到的。

【讨论】:

    【解决方案2】:

    您可以使用find_if 算法来搜索具有相同地址的元素,如下所示:

    auto it = std::ranges::find_if(m, 
        [ptr = std::addressof(*local_it)](const auto& e) -> bool
        {
            return ptr == std::addressof(e);
        }
        );
    

    这里是完整的代码sn-p:

    #include <string_view>
    #include <iostream>
    #include <unordered_map>
    #include <algorithm>
    #include <ranges>
    #include <memory>
    
    int main()
    {
        std::unordered_multimap<int, char> m;
        m.insert({1, 'a'});
        m.insert({1, 'b'});
        m.insert({2, 'c'});
    
        auto local_it = m.begin(m.bucket(1));
        std::cout << local_it->first << local_it->second << '\n';
    
        auto it = std::ranges::find_if(m, 
        [ptr = std::addressof(*local_it)](const auto& e) -> bool
        {
            return ptr == std::addressof(e);
        }
        );
    
        std::cout << it->first << it->second << '\n';
    
        return 0;
    }
    

    运行它here。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-02-21
      • 2022-08-12
      • 1970-01-01
      • 2023-03-31
      • 1970-01-01
      • 2020-06-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多