简体   繁体   English

在自定义迭代器中包装STL容器的最佳方法是什么?

[英]What is the best approach for wrapping an STL container in a custom iterator?

To illustrate, say I have a custom container than makes use of the STL std::vector internally. 为了说明,假设我有一个自定义容器,而不是内部使用STL std::vector If I typedef std::vector<char*>::iterator to my_container::iterator , then dereferencing the iterator will return a char* . 如果我对my_container::iterator输入my_container::iterator std::vector<char*>::iterator my_container::iterator ,那么取消引用迭代器将返回一个char* However, my custom container should hide its internals, meaning I want a dereferencing to return a char . 但是,我的自定义容器应该隐藏其内部,这意味着我想要一个解除引用来返回一个char

How can this be accomplished? 如何实现这一目标?

class my_container {
public:

    typedef std::vector<char*> vector;

private:

    vector vec_;

};

UPDATE: char* is an example. 更新: char*就是一个例子。 It does not mean a C string; 它不代表C字符串; the example would be clearer with an int . 这个例子用int更清楚。

Also, I would like to use std::forward_iterator_tag and std::iterator as this seems a more standard/current approach. 另外,我想使用std::forward_iterator_tagstd::iterator因为这似乎是一种更标准/最新的方法。

If you want your own iterator, just start writing it as a nested class. 如果您想要自己的迭代器,只需将其作为嵌套类开始编写即可。 It will need to wrap a std::vector<char*>::iterator , intercepting the usual operations (eg ++ , * , -- ), something like: 它需要包装一个std::vector<char*>::iterator ,拦截通常的操作(例如++*-- ),例如:

class iterator
{
  public:
    iterator& operator++() { ++i_; return *this; }
    char& operator*() { return **i_; }
    ...etc...

  private:
    std::vector<char*>::iterator i_;
};

If you try it and get stuck, post your attempt and we'll help you further. 如果您尝试并卡住,请发布您的尝试,我们会进一步帮助您。

The best way? 最好的方法? phew!, tough question. 哎呀!这个棘手的问题。

one way is to use the very useful framework that has been created for exactly this purpose by the nice folks at boost.org: 一种方法是使用boost.org上的好朋友为此目的创建的非常有用的框架:

http://www.boost.org/doc/libs/1_58_0/libs/iterator/doc/ http://www.boost.org/doc/libs/1_58_0/libs/iterator/doc/

Use boost::indirect_iterator . 使用boost::indirect_iterator

EDIT: (Untested) 编辑:(未经测试)

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM