C++ 迭代器到 const_iterator

C++ iterator to const_iterator(C++ 迭代器到 const_iterator)
本文介绍了C++ 迭代器到 const_iterator的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 C++ 中从 iterator(该容器类的)获取一个 const_iterator(某个容器类的)?insert_iterator 中的 const_iterator 怎么样?生成的 iterator 应该指向与原始位置相同的位置.

How do I acquire a const_iterator (of some container class) from an iterator (of that container class) in C++? What about a const_iterator from an insert_iterator? The resulting iterator should point at the same spot as the original does.

推荐答案

容器需要提供 iterator 作为可转换为 const_iterator 的类型,所以可以隐式转换:

Containers are required to provide iterator as a type convertible to const_iterator, so you can convert implicitly:

Container::iterator it = /* blah */;
Container::const_iterator cit = it;

std::insert_iterators 是输出迭代器.这无法将它们转换为必须是前向迭代器的常规 Container::iterator.

std::insert_iterators are output iterators. This gives no way to convert them to a regular Container::iterator which must be a forward iterator.

另一种插入迭代器可能允许这样的事情,但从标准函数获得的那些不允许.

Another kind of insert iterator may allow such a thing, but those obtained from the standard functions don't.

我猜你可以在 std::insert_iterator 周围编写自己的包装器,它会暴露受保护的成员 iter,但是:

I guess you can write your own wrapper around std::insert_iterator that exposes the protected member iter, though:

template <typename Container>
class exposing_insert_iterator : public std::insert_iterator<Container> {
public:
    exposing_insert_iterator(std::insert_iterator<Container> it)
    : std::insert_iterator<Container>(it) {}
    typename Container::iterator get_iterator() const {
        return std::insert_iterator<Container>::iter;
    }
};

// ...
std::insert_iterator<Container> ins_it;
exposing_insert_iterator<Container> exp_it = ins_it;
Container::iterator it = exp_it.get_iterator();

这篇关于C++ 迭代器到 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?(易失性成员变量与易失性对象?)