如何删除 const_iterator 的常量?

How to remove constness of const_iterator?(如何删除 const_iterator 的常量?)
本文介绍了如何删除 const_iterator 的常量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为这个问题的扩展const_iterators 更快吗?,我还有一个关于 const_iterators 的问题.如何删除 const_iterator 的常量?尽管迭代器是指针的广义形式,但 const_iteratoriterator 仍然是两个不同的东西.因此,我相信,我也不能使用 const_cast<>const_iterator 转换为 iterators.

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.

一种方法可能是您定义一个迭代器,它移动'直到 const_iterator 指向的元素.但这看起来是一个线性时间算法.

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?

推荐答案

在 C++11 中有一个恒定时间复杂度的解决方案:对于任何序列、关联或无序关联容器(包括所有标准库容器),您可以调用具有空范围的范围擦除成员函数:

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

范围擦除成员函数有一对 const_iterator 参数,但它们返回一个 iterator.因为提供了一个空范围,所以对擦除的调用不会更改容器的内容.

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.

向 Howard Hinnant 和 Jon Kalb 致敬.

这篇关于如何删除 const_iterator 的常量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Rising edge interrupt triggering multiple times on STM32 Nucleo(在STM32 Nucleo上多次触发上升沿中断)
How to use va_list correctly in a sequence of wrapper functions calls?(如何在一系列包装函数调用中正确使用 va_list?)
OpenGL Perspective Projection Clipping Polygon with Vertex Outside Frustum = Wrong texture mapping?(OpenGL透视投影裁剪多边形,顶点在视锥外=错误的纹理映射?)
How does one properly deserialize a byte array back into an object in C++?(如何正确地将字节数组反序列化回 C++ 中的对象?)
What free tiniest flash file system could you advice for embedded system?(您可以为嵌入式系统推荐什么免费的最小闪存文件系统?)
Volatile member variables vs. volatile object?(易失性成员变量与易失性对象?)