valtterihaav
valtterihaav

Reputation: 1

gcc compiler not recognizing iterator substraction

#include <iostream>
#include <iterator> // for iterators
#include <list> // for lists
using namespace std;

void printReverse(const list<int>& lst) {
    using iterator = list<int>::const_iterator;
    iterator iter = lst.begin();
    iterator end_iter = lst.end();
    iterator mid = iter - (end_iter - iter)/2;
}

Does someone know why the gcc compiler reports an issue "error: invalid operands to binary expression ('iterator' (aka '__list_const_iterator<int, void *>') and 'iterator')" on line 5 where I try to calculate the difference between two iterators?

Upvotes: 0

Views: 94

Answers (1)

Vlad from Moscow
Vlad from Moscow

Reputation: 310930

The class template std::list does not have random access iterators. It has bidirectional iterators for which the operator - is not defined.

In any case this expression

iterator mid = iter - (end_iter - iter)/2;
                   ^^^^

does not make a sense.

You could write for example

iterator mid = std::next( std::begin( lst ), lst.size() / 2 );

Upvotes: 1

Related Questions