首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >通过引用返回迭代器

通过引用返回迭代器
EN

Stack Overflow用户
提问于 2021-02-05 08:31:34
回答 1查看 63关注 0票数 0

我想通过引用来访问我的迭代器类

代码语言:javascript
复制
#include <iostream>

template <typename T> class binary_tree;

template <typename T> 
class binary_tree_iterator {
private:
    binary_tree<T>* tree;
    T data;

public:
    binary_tree_iterator(binary_tree<T>* t) : tree(t) {}
    T& operator*() {data = tree->data(); return data;}
    binary_tree_iterator& operator++() {tree = tree->get_node(); return *this;}
    bool operator!=(binary_tree_iterator& rhs) {return tree->data() != rhs.tree->data();}     
};

template <typename T> 
class binary_tree {       
private:
    T t_data;
    binary_tree<T>* node;
    binary_tree_iterator<T>* It;

public:
    binary_tree(T d) : t_data(d), node(nullptr), It(nullptr)
    {}

    T& data() {
        return t_data;
    }
    
    void set_node(binary_tree<T>* node) {
        this->node = node;
    }
    
    binary_tree<T>* get_node() {
        return node;
    }

    binary_tree_iterator<T> begin() {     
        It = new binary_tree_iterator<T>(this);
        return *It;
    }
    
    binary_tree_iterator<T> end() {
        if(node == nullptr) {
            It = new binary_tree_iterator<T>(this);
            return *It;
        } else {
            return node->end();
        }
    }
};

int main() {
    binary_tree<int>* tree = new binary_tree<int>(2);
    tree->set_node(new binary_tree<int>(3));
    //for(auto& x: *tree) <--- does not work
    for(auto x: *tree) {
        std::cout << x << std::endl;
    }
}

我想要在其中使用它的for-range循环看起来类似于for(auto& x: *tree)。我如何给它一个参考?在创建迭代器时,有没有这样做的标准方法?当我返回数据值时,我将其赋值给迭代器数据成员,这样我就可以通过引用返回。我需要用我的迭代器做同样的事情吗?我不认为这是做这件事的标准方法。

EN

回答 1

Stack Overflow用户

发布于 2021-02-05 09:05:08

我想通过引用访问我的迭代器类

我如何给它一个参考?

将函数的返回类型从binary_tree_iterator<T>更改为binary_tree_iterator<T>&。如果你这样做,你必须存储一个迭代器,而不是返回一个新的迭代器,这样你就可以引用它了。大概,它必须存储为成员变量。

在创建迭代器时,有没有这样做的标准方法?

不是的。没有一个标准容器返回对迭代器的引用。

我不认为这是标准的方法。

确实如此。“标准”,也就是常规的做法是而不是返回对迭代器的引用。

我想要在其中使用的

范围循环看起来类似于for(auto& x: *tree)

不需要返回对迭代器的引用来使其工作。如果你看一看标准的容器,你会发现它们都没有返回对迭代器的引用,这样的循环适用于所有的容器。

该循环中的引用被绑定到通过迭代器间接执行的结果。因此,operator*必须返回指向对象的引用。而且,您的operator*确实返回了一个引用。也就是说,通常迭代器会返回对容器中存储的对象的引用;而不是对迭代器中存储的副本的引用。所以,这是非常不合常规的。

完成迭代器的编写后,您会发现循环可以正常工作。

总而言之:你不需要也不应该通过引用返回迭代器。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66055917

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档