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_iterator
s 是输出迭代器.这无法将它们转换为必须是前向迭代器的常规 Container::iterator
.
std::insert_iterator
s 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();
相关文章