以下代碼使用自定義迭代器打印0到9之間的數字。我g++ -std=c++11 -o test test.cpp
C++自定義迭代器構造函數
#include <iostream>
class some_class;
class some_class_iterator : public std::iterator<std::forward_iterator_tag, int>{ private:
friend class some_class;
int pointed;
some_class_iterator(int _pointed): pointed(_pointed){
std::cout << "over here" << std::endl;
}
public:
int poitned;
int operator*(){
return pointed;
}
const some_class_iterator& operator++(){
pointed++;
return *this;
}
bool operator!=(const some_class_iterator& other) const {
return this->pointed != other.pointed;
}
};
class some_class{
public:
typedef some_class_iterator iterator;
iterator begin(){
return some_class_iterator(0);
}
iterator end(){
return some_class_iterator(10);
}
};
int main(){
some_class a;
for (some_class::iterator i = a.begin(); i != a.end(); ++i) std::cout << *i << std::endl;
}
編譯但是,輸出是不是我預計爲over here
打印多次。 例如實際輸出爲
over here
over here
0
over here
1
over here
2
over here
3
over here
4
over here
5
over here
6
over here
7
over here
8
over here
9
over here
那麼,誰是造成對這裏的構造函數的調用?
我的實際問題是二叉搜索樹的迭代器,在構造函數中,我創建了一個FIFO遍歷,根據(in,pre,post)打印節點,因此多次調用構造函數的代價很高。
* High five!* ...和一些填充文本。 –
哎呀..那是一個失敗的問題...... –
@k_kaz Nah,你對未來的調試技術有了一些啓發,所以這最終是一種勝利。 –