簡體   English   中英

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

[英]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_tagstd::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上的好朋友為此目的創建的非常有用的框架:

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

使用boost::indirect_iterator

編輯:(未經測試)

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