[英]What is the best approach for wrapping an STL container in a custom iterator?
为了说明,假设我有一个自定义容器,而不是内部使用STL std::vector
。 如果我对my_container::iterator
输入my_container::iterator
std::vector<char*>::iterator
my_container::iterator
,那么取消引用迭代器将返回一个char*
。 但是,我的自定义容器应该隐藏其内部,这意味着我想要一个解除引用来返回一个char
。
如何实现这一目标?
class my_container {
public:
typedef std::vector<char*> vector;
private:
vector vec_;
};
更新: char*
就是一个例子。 它不代表C字符串; 这个例子用int
更清楚。
另外,我想使用std::forward_iterator_tag
和std::iterator
因为这似乎是一种更标准/最新的方法。
如果您想要自己的迭代器,只需将其作为嵌套类开始编写即可。 它需要包装一个std::vector<char*>::iterator
,拦截通常的操作(例如++
, *
, --
),例如:
class iterator
{
public:
iterator& operator++() { ++i_; return *this; }
char& operator*() { return **i_; }
...etc...
private:
std::vector<char*>::iterator i_;
};
如果您尝试并卡住,请发布您的尝试,我们会进一步帮助您。
最好的方法? 哎呀!这个棘手的问题。
一种方法是使用boost.org上的好朋友为此目的创建的非常有用的框架:
编辑:(未经测试)
struct S
{
using iterator =
boost::indirect_iterator<std::vector<char*>::iterator>;
using const_iterator =
boost::indirect_iterator<std::vector<char*>::const_iterator>;
iterator begin() { return iterator(vec_.begin()); }
iterator end() { return iterator(vec_.begin()); }
const_iterator begin() const { return const_iterator(vec_.begin()); }
const_iterator end() const { return const_iterator(vec_.begin()); }
private:
std::vector<char*> vec_;
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.