如何清除const_iterator的constness? [英] How to remove constness of const_iterator?

查看:233
本文介绍了如何清除const_iterator的constness?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为此问题的扩展 const_iterators 更快吗? ,我有关于 const_iterators 的另一个问题。如何清除 const_iterator 的constness?
虽然迭代器是指针的通用形式,但 const_iterator 迭代器是两个不同的东西。因此,我相信,我也不能使用 const_cast<> const_iterator 转换为一个方法可以是定义一个迭代器,它移动到 const_iterator

/ code> points。但这看起来是一个线性时间算法。



有什么想法是什么是最好的方式来实现这个?

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

range-erase成员函数有一对 const_iterator 参数,但它们返回一个迭代器。因为提供了一个空白范围,所以要清除的调用不会更改容器的内容。



向Howard Hinnant和Jon Kalb提供这个秘诀的小提示


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? Though iterators are generalised form of pointers but still const_iterator and iterators are two different things. Hence, I believe, I also cannot use const_cast<> to covert from const_iterator to iterators.

One approach could be that you define an iterator which moves 'til the element to which const_iterator points. But this looks to be a linear time algorithm.

Any idea on what is the best way to achieve this?

解决方案

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, typename ConstIterator>
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.

这篇关于如何清除const_iterator的constness?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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