How to remove constness of const_iterator?

后端 未结 9 2530
囚心锁ツ
囚心锁ツ 2020-11-27 03:21

As an extension to this question Are const_iterators faster?, I have another question on const_iterators. How to remove constness of a const_iterator

9条回答
  •  误落风尘
    2020-11-27 03:59

    There is a solution with constant time complexity in C++11: for any sequence, associative, or unordered associative container (including all of the Standard Library containers), you can call the range-erase member function with an empty range:

    template 
    typename Container::iterator remove_constness(Container& c, ConstIterator it)
    {
        return c.erase(it, it);
    }
    

    The range-erase member functions have a pair of const_iterator parameters, but they return an iterator. Because an empty range is provided, the call to erase does not change the contents of the container.

    Hat tip to Howard Hinnant and Jon Kalb for this trick.

提交回复
热议问题