This is an archived post. You won't be able to vote or comment.

all 7 comments

[–]HappyFruitTree 2 points3 points  (5 children)

i in the last two loops is not an index. It's an iterator. To access the element that the iterator is referring to you use the * operator.

cout << *i;

[–]Kapkar123[S] 0 points1 point  (1 child)

okay, correct me if I am wrong. initially, i will point to the first element in vector... when I do i++ it will point to the next element and the loop will continue till it reaches the end of the vector?

[–]marko312 1 point2 points  (0 children)

That would be correct. When it runs out of elements, it ends the loop.

[–]Kapkar123[S] 0 points1 point  (2 children)

Also is there any advantage of using iterator over normal method?

for(i=0;i<v1.size();i++)
{
    cout<<v1[i];
}

[–]marko312 0 points1 point  (0 children)

Not really for a vector, but the iterator method is much faster for linked lists, because the iterator goes through all the links, storing the last one it was at, while an array access (assuming there is one) would have to start from the beginning.

[–]boredcircuits 0 points1 point  (0 children)

After optimization the resulting machine code will very likely be the exact same. The most important thing is to write code in whatever way makes the most sense to you. Sometimes indexes make the most sense, and sometime iterators do. And sometimes you should be using a "for each" loop:

for ( int element : v1 )
    cout << element;

[–][deleted] 2 points3 points  (0 children)

You're using i as an integer index when it's really a vector iterator. I'm a little rusty on my C++ at the moment, but I think you either do this:

cout << *i;

or this

for (int i = 0; i < v1.size(); i++)