[英]Why does gcc optimise away this C++11 foreach loop using my custom iterator?
[英]c++11 foreach syntax and custom iterator
我正在編寫一個用於代替STL容器的容器的迭代器。 目前,STL容器正在許多地方使用c ++ 11 foreach語法,例如: for(auto &x: C)
。 我們需要更新代碼以使用包裝STL容器的自定義類:
template< typename Type>
class SomeSortedContainer{
std::vector<typename Type> m_data; //we wish to iterate over this
//container implementation code
};
class SomeSortedContainerIterator{
//iterator code
};
如何讓自動為自定義容器使用正確的迭代器,以便能夠以下列方式調用代碼?:
SomeSortedContainer C;
for(auto &x : C){
//do something with x...
}
一般來說,確保auto為類使用正確的迭代器需要什么?
為了能夠使用基於范圍的for,您的類應該提供const_iterator begin() const
和const_iterator end() const
成員。 你也可以重載全局begin
函數,但在我看來,擁有成員函數更好。 也建議使用iterator begin()
和const_iterator cbegin() const
,但不是必需的。 如果您只是想迭代一個內部容器,那真的很容易:
template< typename Type>
class SomeSortedContainer{
std::vector<Type> m_data; //we wish to iterate over this
//container implementation code
public:
typedef typename std::vector<Type>::iterator iterator;
typedef typename std::vector<Type>::const_iterator const_iterator;
iterator begin() {return m_data.begin();}
const_iterator begin() const {return m_data.begin();}
const_iterator cbegin() const {return m_data.cbegin();}
iterator end() {return m_data.end();}
const_iterator end() const {return m_data.end();}
const_iterator cend() const {return m_data.cend();}
};
如果你想迭代任何自定義,你可能必須將自己的迭代器設計為容器內的類。
class const_iterator : public std::iterator<random_access_iterator_tag, Type>{
typename std::vector<Type>::iterator m_data;
const_iterator(typename std::vector<Type>::iterator data) :m_data(data) {}
public:
const_iterator() :m_data() {}
const_iterator(const const_iterator& rhs) :m_data(rhs.m_data) {}
//const iterator implementation code
};
有關編寫迭代器類的更多詳細信息,請參閱此處的答案 。
你有兩個選擇:
begin
和end
成員函數,可以像C.begin()
和C.end()
一樣C.begin()
; begin
和end
自由函數,可以使用參數依賴查找或命名空間std
查找,並且可以像begin(C)
和end(C)
一樣調用。 正如其他人所說,您的容器必須實現begin()
和end()
函數(或者具有將容器實例作為參數的全局或std::
函數)。
這些函數必須返回相同的類型(通常是container::iterator
,但這只是一個約定)。 返回的類型必須實現operator*
, operator++
和operator!=
。
據我所知, SomeSortedContainer
只需要提供begin()
和end()
。 這些應該返回一個標准的兼容前向迭代器,在你的情況下SomeSortedContainerIterator
,它實際上會包裝一個std::vector<Type>::iterator
。 標准兼容我的意思是它必須提供通常的增量和解引用運算符,還有所有那些value_type
, reference_type
,... typedef,而foreach結構又使用它來確定容器元素的基礎類型。 但是你可能只是從std::vector<Type>::iterator
轉發它們。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.