【问题标题】:How to make an iterator be "automatically dereferenced"?如何使迭代器“自动取消引用”?
【发布时间】:2012-07-09 04:13:46
【问题描述】:

假设我有这样的事情:

class Collection
{
private:
    typedef std::vector< std::shared_ptr<Something> >::iterator Iterator;
    std::vector< std::shared_ptr<Something> > data_;

public:
    Iterator begin() {return data_.begin()}
    Iterator end()  {return data_.end()}
}

当我使用 Collection::Iterator 实例时,我需要取消引用它一次,以获取 std::shared_ptr&lt;Something&gt; 对象并再次获取 Something 对象。

但是如果我想让std::shared_ptr&lt;Something&gt; 只是一个实现细节,那么在一次取消引用之后,我应该得到一个Something 对象是合理的。

即:

Collection collection;
Collection::Iterator it = collection.begin();
Something firstMember = *it;  // instead of the current **it;

我的问题是,我是否需要从头开始将迭代器作为Collection 的嵌套类,并从这里http://www.cplusplus.com/reference/std/iterator/ 实现随机访问迭代器所需的所有功能,还是有一些众所周知的方法?可能是 C++11?

【问题讨论】:

    标签: c++ c++11 iterator


    【解决方案1】:

    听起来您正在实施的内容存在并且称为boost::ptr_vector。 Boost 还提供了a library 来实现更轻松的迭代器。听起来你要找的是boost::indirect_iterator

    【讨论】:

    • boost::indirect_iterator 正是我想要的!谢谢!
    猜你喜欢
    • 1970-01-01
    • 2015-01-13
    • 1970-01-01
    • 1970-01-01
    • 2014-12-26
    • 2020-07-14
    • 2015-09-26
    • 1970-01-01
    • 2016-09-02
    相关资源
    最近更新 更多