簡體   English   中英

從實現operator []的類中自動創建迭代器

[英]Automatically create iterator from class that implements operator[]

假設我有一個實現operator[]的類,例如:

class Array {
public:
  Array(size_t s) : data(new int[s]) {}
  ~Array() { delete[] data; }
  int& operator[](size_t index) {
    return data[index];
  }
private:
  int* data;
};

有沒有一種方法可以從類中創建隨機訪問迭代器,而不必手動創建迭代器類及其所有方法? 我可以手動定義該類,如下所示:

class ArrayIterator : public std::iterator<std::random_access_iterator_tag, int> {
  public:
    ArrayIterator(Array& a) : arr(a), index(0) {}
    reference operator[](difference_type i) {
      return arr[index + i];
    }
    ArrayIterator& operator+=(difference_type i) {
      index += i;
      return *this;
    }
    bool operator==(const ArrayIterator& rhs) {
      return &arr == &rhs.arr && index == rhs.index;
    }

  // More methods here...

  private:
    Array& arr;
    difference_type index;
};

但是,這樣做非常耗時,因為要實現的方法太多,而且帶有operator []的類的每個迭代器都具有完全相同的邏輯。 似乎編譯器可以自動執行此操作,因此有沒有辦法避免實現整個迭代器?

有沒有一種方法可以從類中創建隨機訪問迭代器,而不必手動創建迭代器類及其所有方法?

創建隨機訪問迭代器的最簡單方法是僅使用原始指針,該指針可以滿足RandomAccessIterator概念的所有要求(STL甚至為原始指針提供了默認模板專業化std::iterator_traits ),例如:

class Array {
public:
    Array(size_t s) : data(new int[s]), dataSize(s) {}
    ~Array() { delete[] data; }

    int& operator[](size_t index) {
        return data[index];
    }

    size_t size() const { return dataSize; } 
    int* begin() { return data; }
    int* end() { return data+dataSize; }
    const int* cbegin() const { return data; }
    const int* cend() const { return data+dataSize; }

private:
    int* data;
    size_t dataSize;
};

通過使用operator[]實現隨機訪問運算operator[]可能會起作用,但是效率可能非常低,這就是編譯器不自動執行此操作的原因。 想象一下將operator[]添加到std::list類的類std::list ,其中“轉到元素i”可能要花i步。 然后,根據operator[]遞增迭代器將具有復雜度O(n),其中n是列表的大小。 但是,隨機訪問迭代器的用戶期望一定的效率,通常為O(1)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM