c++ 在标准库或boost中有整数随机访问迭代器吗?

xoefb8l8  于 2022-12-15  发布在  其他
关注(0)|答案(1)|浏览(138)

我试图找到一个整数上的交钥匙迭代器,它支持boost::counting_iterator的所有操作,但也支持一个数字(Iter operator+(Integer num);)的递增和递减;有没有一种简单的方法可以不用自己编写代码(例如,boost中的一个base接受标记并提供一个随时可用的随机访问整数迭代器)?

t40tm48m

t40tm48m1#

What you are asking for is impossible.
counted_iterator is intended to mirror the functionality of the iterator it is given. But it can only work with what it is given. If you give it a random-access iterator, it will mirror that functionality.
If you give it a forward iterator and then allow the user to increment it with any integer, you are lying to the user. Random access iterator incrementing means more than that you can call operator+ with an integer. It means that this operation has O(1) complexity. And if the underlying iterator doesn't have that complexity on its iteration advancement... you cannot manufacture it from outside of the iterator.
Well, you could by heap-allocating an array of iterators of the size determined by the range you're given. But that's a really bad idea.
If you want to increment an iterator a bunch, but you don't know that the iterator is random-access, use std::next or std::advance .

相关问题