std::vector trouble

Started by
4 comments, last by Servant of the Lord 11 years, 3 months ago

Hello, what am i doing wrong in this code:

for(int i = 0; i != m_Inventory.end(); ++i){ //inventory crap }

the problem is in i != m_Inventory.end();

It says that the != operator is unknown. Now i believe this is saying i need to overload the != operator, but why? Thanks for all help.

Advertisement
You're mixing up iterators and integers. If you want to loop over indexes you need to use i != m_Inventory.size(), if you want to loop over iterators you need to use std::vector<whatever>::iterator i = m_Inventory.begin() (or the equivalent such as C++11's auto).

Thanks :)

And if you are using C++11, not only can you use auto like SiCrane mentioned, you can reformat the entire for() loop into a range-style for() loop:

for(const InventoryItem &item : m_Inventory) //Note the single 'colon' instead of two 'semicolons'. { }

(You can also use 'auto' when specifying the element type in the range-for)

It loops over the entire container, and de-references the iterator for you.

And if you are using C++11, not only can you use auto like SiCrane mentioned, you can reformat the entire for() loop into a range-style for() loop:


for(const InventoryItem &item : m_Inventory) //Note the single 'colon' instead of two 'semicolons'.
{
 
}

(You can also use 'auto' when specifying the element type in the range-for)

It loops over the entire container, and de-references the iterator for you.


for(auto const& item : inventory) {
}

In time the project grows, the ignorance of its devs it shows, with many a convoluted function, it plunges into deep compunction, the price of failure is high, Washu's mirth is nigh.

When introducing range-for the first time, I use the explicit type to show that range-for doesn't depend on 'auto', and to illustrate what the range-for is actually doing.

Almost all of my actual uses of range-for() use auto - but I try not to bootstrap too many new concepts together in one snippet or it makes the individual and distinct concepts harder to learn. People don't have to learn what 'auto' means before they can use range-for(). wink.png

This topic is closed to new replies.

Advertisement