0

Consider the following incomplete snippet:

for (std::list<CollidableNode*>::iterator it = m_Enemies.begin(); it != m_Enemies.end();it++)
{
    //for current position+1 to end loop
    for (std::list<CollidableNode*>::iterator jt = it+1; jt != m_Enemies.end();jt++)
    {
        //do stuff
    }
} 

This code produces obvious errors, but illustrates what I'm trying to do, which is: in the nested loop, set the start point of the loop at the current position in the list, plus one position, so that no duplicate checks are carried out.

Considerations are that the list is highly dynamic in size, with the list being checked for items to remove every update, and new items being added often, so that removals will be faster than a vector.

Is it possible to offset the iterator to a desired position, and if so, how do I go about doing that?

Thanks in advance

Ian Young
  • 1,712
  • 1
  • 16
  • 33
  • In C++11, there's `std::next`; you can also write your own in C++03: `template FwdIt next(FwdIt i, int n = 1) { std::advance(i, n); return i; }` – dyp Feb 08 '14 at 21:50
  • 1
    *"Considerations are [...] will be faster than a vector."* Want speed? Measure. ([Hinnant](http://stackoverflow.com/a/18303787/420683)). Also see http://www.youtube.com/watch?v=YQs6IC-vgmo – dyp Feb 08 '14 at 21:55
  • For list to be faster, you basically **have** to be storing iterators between iterations: and even then there is no guarantee. If you are not, `std::remove_if` makes removing and iterating faster on a `vector` than a `list`. There are cases where `list` is faster, but they are **rare**. – Yakk - Adam Nevraumont Feb 08 '14 at 22:40

1 Answers1

0

Probably std::next is what you need.

TNA
  • 2,595
  • 1
  • 14
  • 19