ThePetest ThePetest - 1 year ago 55
C++ Question

operator -> not working for custom input iterator

I have a complex data structure for which I want to define an input iterator. I want to avoid modifying the content through the iterator so

should return a

The problem is that when I try to use
on the iterator with a
method I get an error:

base operand of
has non-pointer type

Here is a minimal example:

// this is supposed to be a much more complex data structure
std::vector<std::string> a = {"a", "b", "c", "d", "e"};

class MyInputIterator : std::iterator<std::input_iterator_tag, std::string>
MyInputIterator(int i = 0)
j = min(i, a.size());

MyInputIterator& operator++()
j = min(j + 1, a.size());
return *this;

const std::string& operator*() const
return a[j];


int j;

int main()
MyInputIterator it(0);
// error: base operand of '->' has non-pointer type 'MyInputIterator'
std::cout << it->size() << std::endl;

return 0;

Answer Source

You should add this to your iterator

const std::string* operator->() const
    return &a[j];

Now your main will work