Search code examples
c++settraversal

Traversing through a set from a particular index to a particular index


I have an iterator. Say I need to traverse the set not from the beginning but from some particular point. Also it is quite difficult for me to get the values stored in the sets as they are pointers. So how to i modify my code to traverse through my sets from a point that is not the begining. ?

Here is the code:

for(iter=make.at(level).begin();iter!=make.at(level).end();iter++)
{
Function(*iter);
}

Using this gives an error:

for(iter=make.at(level).begin()+10;iter!=make.at(level).end();iter++)
    {
    Function(*iter);
    }

Solution

  • There are different types of iterators: ForwardIterator, BidirectionalIterator, and RandomAccessIterator.

    ForwardIterator allows you to move forward only, using the increment operator. BidirectionalIterator allows both directions. RandomAccessIterator allows any advancement, including operator+ and operator-.

    The one you're thinking in terms of is RandomAccessIterator, like the one found in std::vector. What std::set uses, though, is the BidirectionalIterator. That means you can only increment and decrement.

    Therefore, you need to make your iterator outside of your loop and advance it forward ten times. To make it simple, std::advance does this, and has different compatibility for BidirectionalIterator, as well as ForwardIterator (linear time because of only one increment at a time), and RandomAccessIterator (constant time due to operator+).

    std::set<T>::iterator iter = make.at(level).begin(); //more C++03 way
    auto iter = std::begin (make.at(level)); //more C++11 way
    std::advance (iter, 10); //start iterator 10 elements past beginning
    for (...)