Bwomchickabowow
Bwomchickabowow

Reputation: 57

How to return non-const iterator from function taking a const reference to a container

I am trying to write a template function to return the lexicographical last element in a container.

From my understanding of const correctness, since the function doesn't modify the template argument reference it should be const correct. How would I return a non-const iterator?

In other words, the function doesn't modify the containers elements because it is constant, but that guarantee shouldn't extend to the returned iterator should it?

I wish to express that the function does not modify anything but the returned iterator could allow the caller to do so.

#include<iterator>

template<typename T>
typename T::iterator lexicographical_last(const T& container)
{
  typename T::const_iterator b, last = container.begin();
  while (b != container.end())
    {
      if (b < last) last = b;
      ++b;
    }
  return last;
}

Upvotes: 2

Views: 2110

Answers (1)

jwm
jwm

Reputation: 1844

When you passed "container" by const reference, you are making a promise that this function won't modify it. That includes giving a non-const_iterator back.

If you need a non-const_iterator back, provide an overload that takes a mutable reference

template<typename T>
typename T::const_iterator lexicographical_last(const T& container);
template<typename T>
typename T::iterator lexicographical_last(T& container);

Upvotes: 4

Related Questions