ThePetest ThePetest - 3 months ago 11
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

operator*
should return a
const
reference.

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


base operand of
->
has non-pointer type
MyInputIterator



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>
{
public:
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];
}

...

private:
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

You should add this to your iterator

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

Now your main will work

Comments