Johan Hjalmarsson
Johan Hjalmarsson

Reputation: 3493

forloop, iterators and vectors doesn't cooperate with me

Why does this work fine for me:

 for(int i = 0; i < vec.size(); i++)
    {
        os << vec[i] << " ";
    }

while this doesn't:

 for(vector<int>::iterator it = vec.begin(); it < vec.end(); it++)
    {
        os << vec[*it] << " ";
    }

Upvotes: 1

Views: 102

Answers (2)

cnicutar
cnicutar

Reputation: 182664

You should be printing *it instead of using it as the index and you should probably change the condition to it != vec.end().

Upvotes: 10

Luchian Grigore
Luchian Grigore

Reputation: 258618

You're using the iterator wrong, it should be:

for(vector<int>::iterator it = vec.begin(); it < vec.end(); it++)
{
    os << *it << " ";
}

Your code just attempts to print the element at index *it, which might not even be valid.

Upvotes: 5

Related Questions