Jump to content
  • Advertisement
Sign in to follow this  
Nebu

vector iterator question

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

If you intended to correct an error in the post then please contact us.

Recommended Posts

vector<int> list;
for(int i=0;i<10;i++)
     list.push_back(i+1);

Now lets say I want the iterator of the 5th position. I know I can loop to it but would the following be valid? :
vector<int> ::iterator it = list.begin()+4;

I know this works but I'm not sure if its safe. Thanks.

Share this post


Link to post
Share on other sites
Advertisement
It's as safe as any other iterator. Like all std::vector<>::iterators, though, it can be invalidated by modifying the list (e.g. if .capacity() changes on account of a .reserve(...), a .resize(...), or an insertion such as .push_back(...), as well as any iterator at or after an insertion or removal even if it doesn't change .capacity())

Share this post


Link to post
Share on other sites
I'm pretty sure that works - I read somewhere that std::vector iterators are random-access (+ and - can be used). If there's no particular reason you need an -iterator- at that location, though, why not just use vector.at(index) or vector[index]?

EDIT: And this may just be nitpicky, but that's how compilers can be too... that space between "vector<int>" and "::iterator" might cause problems. But I don't know, I didn't try it.

EDIT 2: And of course I notice that you said "you know it works". Well, it's safe in that it's not some kind of ugly hack: that functionality is built into the iterator anyways. I'd personally use that instead of a loop if I could, just because it's less typing...

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!