继承自定义类的std :: vector :: iterator吗? [英] Inheriting std::vector::iterator for custom class?

查看:139
本文介绍了继承自定义类的std :: vector :: iterator吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在实现一个自定义类,该类包含一个STL std::vector作为中心数据成员. 现在,我希望此类提供一个迭代器,该迭代器只需要对该向量进行迭代,并且还可以与基于C ++ 11范围的迭代一起使用. 以某种方式从std::vector::iterator继承迭代器是非常诱人的,因为它应该做完全相同的工作.这有可能还是我需要实现一个完全自定义的迭代器?

I am implementing a custom class that contains an STL std::vector as central data member. Now, I would like this class to provide an iterator, which merely needs to iterate through this vector and also works with C++11 range based iteration. It is very tempting to just somehow inherit the iterator from std::vector::iterator as it is supposed to do exactly the same job. Is this possible or do I need to implement a completely custom iterator?

class Custom {
private:
  std::vector<double> _data;
public:
  class iterator {
    // Want this to provide an interface to iterate through _data
    // ...
  };
  // ...
};

Custom C;
// Populate C with data ...
for (const auto& item : C) {
  // This should print the elements within _data.
  std::cout << item << std::endl;
}

推荐答案

您不需要从迭代器本身继承.您可以只为std::vector<double>所使用的迭代器提供接口.

You don't need to inherit from the iterator itself. You can just provide interfaces for the iterators used by the std::vector<double>.

这是一个简短的摘要:

#include <vector>
#include <iostream>

class Custom {
private:
  std::vector<double> _data;
public:
  explicit Custom(std::initializer_list<double> init) : _data(init) {}

  using iterator = std::vector<double>::iterator;
  using const_iterator = std::vector<double>::const_iterator;

  iterator begin()
  {
    return _data.begin();
  } 

  iterator end()
  {
    return _data.end();
  } 

  const_iterator cbegin() const
  {
    return _data.cbegin();
  } 

  const_iterator cend() const
  {
    return _data.cend();
  } 
};

int main()
{
  Custom C({ 1.0,2.0,3.0,4.0,5.0 });
  for (const auto &item : C)
  {
    std::cout << item << "\n";
  } 

  return 0;
}

这篇关于继承自定义类的std :: vector :: iterator吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆