• 12
• 12
• 9
• 10
• 13

Compile Error trying to store an iterator

This topic is 4460 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

Recommended Posts

Hi, I am using C++. I have a vector full of items. I want to set an iterator to point to an element in the vector, based on the index (as shown below):
vector<CItem>::iterator itItem=m_vctItems[nIndex];


I get this compile error though:
Quote:
 Main.cpp(1143) : error C2440: 'initializing' : cannot convert from 'std::allocator<_Ty>::value_type' to 'std::vector<_Ty>::iterator' with [ _Ty=CItem ] and [ _Ty=CItem ] No constructor could take the source type, or constructor overload resolution was ambiguous.
So, what is wrong?

Share on other sites

vector<CItem>::iterator itItem= m_vctItems.begin() + nIndex;

When you access a vector with an index, it returns the CItem aka value_type. You instead want an iterator, so you can get that with calling begin() and adding the offset that you want because a vector has a random access iterator.