Anubhav Agarwal
Anubhav Agarwal

Reputation: 2062

Compare the Current And Next Element of A set

I want to compare the current and next element of a set of addresses . I tried the following code

    struct Address{
          string state;
          string city;
    }

    if((*it).state == (*(it+1)).state){
    } 

But the compiler gave an error that no match for operator+ in "it+1". On cplusplus.com I found that + operator is not supported for set containers. So I am unable to figure out a way to access both the current and the next element of a set in the same if statement.

Upvotes: 0

Views: 2271

Answers (3)

Grizzly
Grizzly

Reputation: 20211

As you already found out the operator + is not supported for std::set iterators, since those are only bidirectional iterators and not random access iterators. So if you want to access the next element at the same time as the current one you have to make a copy and increment that one:

std::set<Address>::iterator next_it = it;
++next_it;
if(it->state == (next_it)->state)

If you are using c++11 this code can be simplyfied using the std::next function found in <iterator>(which basically does the same thing):

if(it->state == std::next(it)->state)

Of course writing that function is pretty trivial, so you could always write your own next when coding pre C++11 .

Also: Remember to make sure that the next iterator isn't equal to set.end()

Upvotes: 0

zch
zch

Reputation: 15278

But ++ is provided, so you can write:

?::iterator next = it;
next++;

Upvotes: 1

Benjamin Lindley
Benjamin Lindley

Reputation: 103751

Just create a copy of the iterator, advance it(++), then compare. Or, if your standard library has it, you can use the c++11 next function from the <iterator> library.

if(it->state == std::next(it)->state)

Upvotes: 1

Related Questions