Ajouve
Ajouve

Reputation: 10049

loop in vector c++ using iterator

I have this code:

std::vector<A>::iterator it;
for(auto it = m_vA.begin(); it != m_vA.end(); it++)

and I gon an error:

ISO C++ forbids declaration of 'it' with no type
cannot convert '__gnu_cxx::__normal_iterator<A* const*, std::vector<tp::Vehicule*, std::allocator<A*> > >' to 'int' in initialization

and If I remove the auto

erreur: no match for 'operator=' in 'it = ((const B*)this)->B::m_vA.std::vector<_Tp, _Alloc>::begin [with _Tp = A*, _Alloc = std::allocator<A*>]()'

B is the class with my loop

Thanks

Upvotes: 1

Views: 374

Answers (4)

user2030052
user2030052

Reputation:

If you do have C++11 enabled, then why are you using auto like this? Simply use a range-based for loop:

for (auto i : m_vA)
    // do stuff here with i

Also, the problem with your code is that you specified the type of it, so there's no point in using auto in the for loop. Again, if you're using C++11, you should use the above loop, because it's far easier to write and understand.

Upvotes: 1

Slava
Slava

Reputation: 44268

For auto you seem not to have c++11 enabled, if you enable it, you should remove this line:

std::vector<A>::iterator it;

If you cannot use c++11 and for error after you remove auto, looks like you put this code into const method, so replace iterator with const_iterator:

std::vector<A>::const_iterator it;
for(it = m_vA.begin(); it != m_vA.end(); it++)

You can also make it one line, if you do not need this iterator after the loop:

for(std::vector<A>::const_iterator it = m_vA.begin(); it != m_vA.end(); it++)

Upvotes: 2

masoud
masoud

Reputation: 56539

To solve your problem remove auto keyword.

You must have C++11 enabled to use auto like that. If you are using gcc compiler, you can enable it by -std=c++11 or -std=c++0x compiler's switch.

Currently it's using auto keyword inherited by older C compilers which simply will be omited. Compiler thinks you're declaring it again but without type.

Upvotes: 1

Creak
Creak

Reputation: 4565

From what I see, you are in a const method, you should use const_iterator, or remove the const.

And auto isn't needed if you declare your variable before. It won't produce an error, just a warning, but you've got to choose one way or the other ;)

Upvotes: 1

Related Questions