Why is adding a number to a container associative iterator impossible?

I have std :: set, and I wanted to iterate through pairs of elements in the set, so I wrote 2 for such loops:

for(std::set<T>::iterator i=mySet.begin();i!=mySet.end();++i)
{
    for(std::set<T>::iterator j=i+1;j!=mySet.end();++j)
    {
        // do something
    }
}

The compiler told me that I cannot add numbers to the iterator. However, I can increase and decrease them. Workaround I find that I can skip the first iteration:

for(std::set<T>::iterator i=mySet.begin();i!=mySet.end();++i)
{
    std::set<T>::iterator j=i;
    for(++j;j!=mySet.end();++j)
    {
        // do something
    }
}

Why can't I just add a number, why do I need to increment?

+3
source share
5 answers

, , , . . [] std:: list?

+5

, Boost :

for(std::set<T>::iterator i=mySet.begin();i!=mySet.end();++i)
{
    for(std::set<T>::iterator j=boost::next(i);j!=mySet.end();++j)
    {
        // do something
    }
}

,

for(std::set<T>::iterator i=mySet.begin();i!=mySet.end();/* NOTHING */)
{
    std::for_each(++i, mySet.end(), /* do something*/ );
}
+2

, .

Set , , .

0

Look here in the definition of iterators. The method you are looking for is defined only for container iterators, which allows random access, which the set does not support.

0
source

Your question has already been answered, but note that you can shorten your code as follows:

for(std::set<T>::iterator i=mySet.begin();i!=mySet.end();++i)
{
    for(std::set<T>::iterator j=i;++j!=mySet.end();)
    {
        // do something
    }
}
0
source

Source: https://habr.com/ru/post/1777043/


All Articles