Is is possible to make STL-Iterator to work with user defined class ,like the one below?
#include <iostream>
#include <stdexcept>
using namespace std;
template <class T>
class Array
{
public:
T& operator[] (unsigned i) throw(out_of_range)
{ return data_; }
protected:
T data_[100];
};
int main(void)
{
Array<int> a;
a[0] = 42;
a[1] = 10;
cout<<a[0]<<endl;
#ifdef TEMP
//How to make this work
for ( Array<int>::iterator it=a.begin() ; it != a.end(); it++ )
cout << " " << *it;
#endif
}
If yes,please explain with example
You'd be writing your own iterator, not using STL's iterator. It involves nested classes.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
class array
{
public:
array(int Size)
{
values=(int *)malloc(sizeof(int) * Size);
len=Size;
memset(values, 0, Size*sizeof(int));
}
int &operator[] (int i) { return(values); }
int size() { return(len); }
class iterator
{
public:
iterator(array *A=NULL, int off=0) { a=A; p=off; }
bool operator ==(const iterator &oe)
{ return( (oe.a == a) && (oe.p == p) ); }
bool operator !=(const iterator &oe)
{ return(! ((*this) == oe) ); }
iterator &operator++(void)
{
if(p < a->size()) p++;
return(*this);
}
int &operator *(void) { return((*a)[p]); }
private:
array *a; int p;
};
iterator begin()
{ return(iterator(this)); }
iterator end()
{ return(iterator(this, len)); }
private:
int *values;
int len;
};
int main(void)
{
int n;
array arr(10);
for(n=0; n<10; n++) arr[n]=n;
array::iterator i=arr.begin();
while(i != arr.end())
{
printf("got %d\n", *i);
++i;
}
}
Thanks for your time in explaining me with an example.