3 ms·
You can think of it as implementing `seek`, not just `next`. `RandomAccessIterator` implements the `+=` and `-=` operations that `BidirectionalIterator` does n
by missblit 6y ago
You can think of it as implementing `seek`, not just `next`.
`RandomAccessIterator` implements the `+=` and `-=` operations that `BidirectionalIterator` does not. Algorithms that accept `RandomAccessIterator` can then assume that calling += is possible.
- arcticbull 6y agoWhat's the advantage to using a random access iterator over a get() indexed? Like to me the point of an iterator is that it abstracts over access kind, and exposes the minimum viable view, which is sequential forward and possibly backward access. If you want indexed access why wouldn't you just, you know, use anything that implements operator[]?
- missblit 6y agoJust that iterators is the API that C++ settled on for doing this in a generic way (well concepts in C++20, but I haven't learned that yet). It's totally 100% kosher to write a function that calls `.at()` instead of `operator+=`. As long as it only needs to work on vectors, strings, or other stuff with a `.at()` method. But if the function works on iterators instead it can work on ANY data structure that also fulfills the requirements of RandomAccessIterator API. String Views, raw pointers, a 3rd party Cord library, etc. There's no inherent meaning to the iterator API requiring `operator+=` instead of something closer to `get()`, except that it means that the iterator itself doesn't need to know anything about container bounds (like I said above, raw pointers work as RandomAccessIterators).
- Too 6y ago[] alone doesn't imply that the view is sequential. Binary search for example requires both sequential items and indexed access. You can't binary search an std::map even if it implements [].
- josefx 6y agoYou need an additional API to create views/sublists if you want to transparently operate on sub ranges and if you want to return a found index you may need to convert its value to apply to a parent view.