Sign in to follow this  
Crusable77

std::vector trouble

Recommended Posts

Crusable77    594

Hello, what am i doing wrong in this code:

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

 

the problem is in [code]i != m_Inventory.end();[/code]

 

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.

Share this post


Link to post
Share on other sites
SiCrane    11839
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).

Share this post


Link to post
Share on other sites

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:

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

(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.

Share this post


Link to post
Share on other sites
Washu    7829
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) {
}

Share this post


Link to post
Share on other sites

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

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this