繁体   English   中英

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

[英]operator -> not working for custom input iterator

我有一个复杂的数据结构,我想要定义一个输入迭代器。 我想避免通过迭代器修改内容,因此operator*应该返回一个const引用。

问题是,当我尝试在const方法的迭代器上使用->时,我得到一个错误:

基本操作数->具有非指针类型MyInputIterator

这是一个最小的例子:

// 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;
}

您应该将它添加到迭代器中

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

现在你的main工作

要在MyInputIterator类上调用operator->() ,必须先实现它。

在你的情况下,它看起来像:

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

暂无
暂无

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

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