Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Initialize std::vector<T>::iterator with arbitrary element?

5 views
Skip to first unread message

Rune Allnor

unread,
Feb 1, 2010, 5:50:48 AM2/1/10
to
Hi all.

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

Vladimir Jovic

unread,
Feb 1, 2010, 6:03:18 AM2/1/10
to

Richard Herring

unread,
Feb 1, 2010, 9:33:49 AM2/1/10
to
In message
<dae03e12-31c3-4336...@e37g2000yqn.googlegroups.com>,
Rune Allnor <all...@tele.ntnu.no> writes

>Hi all.
>
>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;

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

Juha Nieminen

unread,
Feb 2, 2010, 11:01:29 AM2/2/10
to
Rune Allnor wrote:
> One naive idea - which even compiles - is
>
> i = v.begin() + n;

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 ---

0 new messages