I have an std::set and I wanted to iterate trough the element pairs in the set so I wrote 2 for loops like this:
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 can’t add numbers to iterator. However I can increment and decrement them. A 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 I can’t just add a number why I have to increment?
you can do this only with random access iterator, so the reasons are the same as for not having an indexoperator on containers when it would be slow. See also Why isn't there an operator[] for a std::list?