![](/img/trans.png)
[英]Instantiate object with parameters in a different file that I have created it (C++)
[英]How can I build iterator for object that I have created in C++
我想建立一個簡單的迭代器,例如-在類“ myVector”中:
#include <iostream>
using namespace std;
#define maxSize 10
class myVector {
private:
int *arr;
int sp;
public:
myVector() {
arr = new int[maxSize];
sp = 0;
}
bool add(int num) {
if (sp==maxSize) return 0;
arr[sp] = num;
sp++;
return 1;
}
};
在示例中-我構建了一個生成myVector類型對象的類。 現在,我想使用運算符++構建迭代器,以在向量的私有數組上運行。
非常感謝你
您必須支持std::iterator_traits<YourIterator>
。 最簡單的方法是使用適當的參數從std::iterator<?>
繼承。
為此,您必須確定迭代器類別。 這決定了您保證在操作員和行為上都將支持的內容。
現在, boost
具有一些幫助程序類型,可以使編寫迭代器更加容易。 考慮使用boost
。 但是沒有它們,編寫基本的迭代器並不是沒有可能。
在上面的特定情況下,指針是針對您的問題的有效迭代器。 而且比以上任何一個選項都容易。 將其用作您的第一個迭代:KISS。 請注意,指針免費提供了std::iterator_traits
支持。
為了使對象可迭代(並支持for(auto&&x:c)
語法),請在與生成迭代器的類相同的名稱空間中編寫一個免費的begin
和end
函數,或者添加執行相同操作的begin()
和end()
方法。 我也傾向於增加size
和empty
和front
和back
,因為我發現它們非常有用。 舉個例子:
T& back(){return *std::prev(end());}
T const& back()const{return *std::prev(end());}
您需要編寫這樣的內容。
class myVector {
class myIterator {
private:
int *position; //operator ++ increment this position
public:
myIterator operator++(){
//increment position here
}
int& operator*(){
//return *pos
}
bool operator==(const myIterator &it)const {
//check that pos and it.pos are the same
}
};
};
這將起作用,但不會成為STL兼容的迭代器,為此,您還需要添加多個typedef,例如,您的迭代器的類型(在您的情況下,您有一個輸入迭代器)。 如果要使用STL迭代器,最簡單的方法是使用Boost Facade迭代器 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.