如何从带有const引用的函数返回非const迭代器到容器 [英] How to return non-const iterator from function taking a const reference to a container

查看:191
本文介绍了如何从带有const引用的函数返回非const迭代器到容器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个模板函数来返回容器中的字典最后一个元素。

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

从我对const正确性的理解,因为函数没有修改模板参数引用应该是const正确的。我将如何返回非const迭代器?

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


推荐答案

当你通过容器时通过const引用,您承诺此函数不会修改它。这包括给一个非const_iterator。

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.

如果你需要一个非const_iterator,请提供一个带有可变引用的重载

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

这篇关于如何从带有const引用的函数返回非const迭代器到容器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆