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 typeMyInputIterator
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;
}
You should add this to your iterator
const std::string* operator->() const
{
return &a[j];
}
Now your main
will work
In order to call operator->()
on your MyInputIterator
class you must first implement it.
In your case it would look something like:
const std::string* operator->() const
{
return &a[j];
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.