c++ - 使迭代器取消引用对象

标签 c++

我有一个简单的容器类,例如:

class SimpleContainer {
    using iterator = std::vector<Contained*>::iterator;

    std::vector<Contained*> items_; // Note that 'Contained' is polymorphic.

public:
    iterator begin() { return items_.begin(); }
    iterator end() { return items_.end(); }    
};

很简单。但是当我在例如 for 循环中使用它时,我必须手动取消引用该项目,如:

SimpleContainer container;
for (auto item : container) {
    cout << *item << endl; // Dereferencing here is ugly
}

是否有一种简单的方法可以让迭代器为我自动取消引用,或者我是否需要编写一个具有该行为的新迭代器?

最佳答案

如果使用 boost 是可以接受的,indirect_iterator 就是为此目的创建的。使用

using iterator = boost::indirect_iterator<std::vector<Contained*>::iterator>;

然后你需要修改begin()end()

iterator begin() { return boost::make_indirect_iterator(items_.begin(); }

更多详情请访问 http://www.boost.org/doc/libs/1_56_0/libs/iterator/doc/indirect_iterator.html

关于c++ - 使迭代器取消引用对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25406667/

相关文章:

C++:如何将数组中的 2 个字节转换为无符号短

c++ - 澄清没有#includes 的 header

c++ - 将现有的 shared_ptr 附加到 shared_ptr 的 vector

c++ - 有没有办法在 Linux 上用 C++ 原子地刷新二进制信号量?

c++ - 如何从非指针对象创建 std::shared_ptr?

c++ - 为什么使用预编译头文件 (C/C++)?

c++ - 重载运算符或数字转换的问题

c++ - 创建包含已分配数组的 unique_ptr 的正确方法

c++ - 为 ActiveX 控件编写包装类

c++ - 在 OpenGL 场景中创建聚光灯