Jump to content
  • Advertisement
Sign in to follow this  
supagu

[stl] iterator from index

This topic is 4447 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

i have a list of "things" stored in an stl container, i've tried a list and vector. I add a bunch of "things" to the end, but i want to keep an iterator to the begining of the new "things" as i have some code that iterates over the old things and some code that iterates over the new things. SO what i tried was to keep an iterator to this dividing point in my list, but this didnt work. so i thought about a vector, as i wouldnt have to keep a iterator that may expire, instead i thought i would keep the index, but it seems i cant generate an iterator from an index with a vector. Any recommendations for a solution to my problem? i could use indexes instead but it wouldn't be as such an elegant solution as iterators

Share this post


Link to post
Share on other sites
Advertisement
What you described should work with std::list. What you don't want to do, however, is first of all remember list.end() before adding your new items. What you do want to do is remember the iterator to the first new item you add.

std::list<int>::iterator AddToList(std:list<int>& List, int NumberOfNewValues)
{
std::list<int>::iterator iNewlyAdded;
if (NumberOfNewValues > 0)
{
iNewlyAdded = List.insert(List.end(), GenerateNewValue());
}
for (int i = 1; i < NumberOfNewValues; ++i)
{
List.push_back(GenerateNewValue());
}
return iNewlyAdded;
}



Don't try this with std::vector, however, since iterators can become invalidated when adding new elements (this happens if the internal array needs to be reallocated). Indexes, as you determined, will work however. Also, as a shortcut to SiCrane's code, you can simply write "container.begin() + index". However, this will only work when you know that the container supports random-access iterators. std::advance() works on any iterator (with restrictions on whether or not the amount to advance should be non-negative, depending on type of iterator). std::advance() will automatically do the shortcut above if it can, but I am sometimes lazy and like to avoid the two lines it takes to perform a std::advance() call, assuming I don't already have an iterator variable available to use.

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.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!