c++ - 自定义未绑定(bind)数组的迭代器

标签 c++ stl iterator std

我实现了自己的小型 UnboundArray 类:

template <typename T>
class UnboundArray {
private:
    std::vector<T> elementData;
public:
    ...
    std::size_t size()
    {
        return elementData.size();
    }
};

我有一个类,我想在其中使用我的 UnboundArray,特别是我需要在 UnboundArray 元素上使用 for 循环:

for (auto const &row : unbound_arrays) {
// loop over unbound array of unbound arrays and call its size method or something else
}

我真的是 C++ 迭代器的新手,不知道我应该遵循什么路径。我应该从头开始实现我的迭代器,还是应该在我的 UnboundArray 中创建一个类型为 std::iterator 的成员?

最佳答案

如果您主要需要使用 range based for loop对于自定义类 UnboundArray,您可以从为 UnboundArray 实现 begin()end() 方法开始:

auto begin() { return std::begin(elementData); }
auto end() { return std::end(elementData); }

所以循环有效:

UnboundArray<int> unbound_array;

for (auto const &elem: unbound_array) { // ... }

wandbox example


请务必注意,您需要 const 重载才能遍历 const UnboundArray:

auto begin() const { return std::cbegin(elementData); }
auto end() const { return std::cend(elementData); }

关于c++ - 自定义未绑定(bind)数组的迭代器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48597135/

相关文章:

c++ - SDL + OpenGL : access violation when creating buffer

Java 字典迭代器类型问题

java - 有没有办法在Java中foreach迭代器?

c++ - 为什么vector template function assign有两个版本来区分

c++ - 如何比较格式为 "Month Date hh:mm:ss"的两个时间戳以检查 +ve 或 -ve 值

c++ - 在应用程序中禁用 Vista 风格的控件

c++ - boost::multiprecision 从整数转换为 cpp_dec_float 编译错误

c++ - 如何使用 std::unique 删除 vector 中的唯一字符 (c++)

包含任何类型的模板类对象的 C++ 映射

c++ - 如何在不授予私有(private)成员访问权限的情况下在 C++ 中隐藏 STL 仿函数结构