mardi 30 janvier 2018

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;
}

Aucun commentaire:

Enregistrer un commentaire