titus
titus

Reputation: 5784

plus operator for set iterator doesn't work

this works fine, but seems rather ugly

#include <iostream>
#include <set>
#include <set>

int main ()
{
    std::set<int> v;
    for(int i=0;i<5;i++)
    {
        v.insert(i);
    }
    for(std::set<int>::iterator it1 = v.begin(); it1!=v.end(); ++it1)
    {
        std::set<int>::iterator it2=it1;
        std::advance(it2,1);
        for(; it2!=v.end(); ++it2)
        {
           std::cout<<*it1<<" "<<*it2<<std::endl;
        }
    }

    return 0;
}

this doesn't compile because set::iterator doesn't have + operator, why is that? is there an elegant way around this?

#include <iostream>
#include <set>
#include <set>

int main ()
{
    std::set<int> v;
    for(int i=0;i<5;i++)
    {
        v.insert(i);
    }
    for(std::set<int>::iterator it1 = v.begin(); it1!=v.end(); ++it1)
    {
        for(std::set<int>::iterator it2=it1+1; it2!=v.end(); ++it2)
        {
        std::cout<<*it1<<" "<<*it2<<std::endl;
        }
    }

    return 0;
}

Upvotes: 1

Views: 864

Answers (2)

ravi
ravi

Reputation: 10733

'+' operation is only provided for Random access iterators. And std::set doesn't use Random access iterators.

Upvotes: 2

juanchopanza
juanchopanza

Reputation: 227390

std::set's iterators are bidirectional iterators, because internally sets are node-base structures. Applying an offset with + would be O(N) for this kind of structure, so its iterators don't directly support that. This operation is supported for random access iterators, for which it is O(1).

Upvotes: 3

Related Questions