Suppose I have a vector v,
std::vector<T> v;
and corresponding iterator i
std::vector<T>::iterator i;
Now I want to initalize i to point to some
arbitrary element v[n] in the vector.
What is the best practice way to do this
initialization? I have only seen initalizations
to either v.begin() or v.end().
One naive idea - which even compiles - is
i = v.begin() + n;
However, table 7.6 in Josuttis' "The C++ Standard Library"
indicates there should be a way to index reative to
the iterator, something like
std::vector<T>::iterator j=i[n];
If correct, I would expect that something like
i = (v.begin())[n];
also would work. Which it doesn't. So did I
misunderstand something?
Rune
Yes, read here :
http://www.parashift.com/c++-faq-lite/how-to-post.html#faq-5.8
That's fine (and efficient) for a random-access iterator.
>
>However, table 7.6 in Josuttis' "The C++ Standard Library"
>indicates there should be a way to index reative to
>the iterator, something like
>
>std::vector<T>::iterator j=i[n];
ITYM T t = i[n];
>
>If correct, I would expect that something like
>
>i = (v.begin())[n];
>
>also would work. Which it doesn't. So did I
>misunderstand something?
A level of indirection. i[n] returns a reference to an element of the
vector, not an iterator.
--
Richard Herring
Why is it naive? That's the standard way of doing it (and not only
with std::vector iterators, but with any data container with random
access iterators).
--- news://freenews.netfront.net/ - complaints: ne...@netfront.net ---