简体   繁体   English

operator - >不适用于自定义输入迭代器

[英]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. 我想避免通过迭代器修改内容,因此operator*应该返回一个const引用。

The problem is that when I try to use -> on the iterator with a const method I get an error: 问题是,当我尝试在const方法的迭代器上使用->时,我得到一个错误:

base operand of -> has non-pointer type MyInputIterator 基本操作数->具有非指针类型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;
}

You should add this to your iterator 您应该将它添加到迭代器中

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

Now your main will work 现在你的main工作

In order to call operator->() on your MyInputIterator class you must first implement it. 要在MyInputIterator类上调用operator->() ,必须先实现它。

In your case it would look something like: 在你的情况下,它看起来像:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM