Sign in to follow this  
supagu

[stl] iterator from index

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

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