1

I have been searching for a method to convert a constant iterator to an iterator and I stumbled upon this StackOverflow question:

How to remove constness of const_iterator?

An answer suggested to use this template function:

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

What I am confused about is how to go about implementing (calling) this function within my main code. I plan to use this code to convert a CGAL Ccb_halfedge_const_iterator to its non-constant counterpart. If the name of my Ccb_halfedge_const_iterator is dcel_circulator, how would I call this function:

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

within my main code?

2 Answers2

1
#include <iterator>
#include <vector>


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

int main()
{

    std::vector<int> vec = {};
    std::vector<int>::const_iterator iter = vec.begin();
    std::cout << std::is_same_v<decltype(iter), std::vector<int>::const_iterator> <<" - "
              << std::is_same_v<decltype(iter), std::vector<int>::iterator>
              <<std::endl;

    auto iter2 = remove_constness(vec, iter);

    std::cout << std::is_same_v<decltype(iter2), std::vector<int>::const_iterator> << " - "
              << std::is_same_v<decltype(iter2), std::vector<int>::iterator>
              << std::endl;

}
0

If you have access to the container, why not just reproduce a new iterator to the same place. aka something like:

template <typename Container, typename ConstIterator>
typename Container::iterator remove_constness(Container& c, ConstIterator it)
{
    auto out_it = std::begin(c);
    std::advance(out_it, std::distance(std::cbegin(c), it));
    return out_it;
}

Caveat: Wont work for reverse iterators, but typename Container::iterator excludes reverse iterators anyway.

Fantastic Mr Fox
  • 32,495
  • 27
  • 95
  • 175