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

R

Rune Allnor

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
 
V

Vladimir Jovic

Rune said:
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?

Yes, read here :
http://www.parashift.com/c++-faq-lite/how-to-post.html#faq-5.8
 
R

Richard Herring

In message
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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top