![](/img/trans.png)
[英]Overloaded `!=` operator in custom iterator class is not working properly
[英]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.