STL Iterator and user-defined class
Is is possible to make STL-Iterator to work with user defined class ,like the one below?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
|
#include <iostream>
#include <stdexcept>
using namespace std;
template <class T>
class Array
{
public:
T& operator[] (unsigned i) throw(out_of_range)
{ return data_[i]; }
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
In all cases STL "iterators" are types owned by the container. You have to do the same
thing... ie, make your own iterator type for Array<>.
You will need to research what are the requirements for iterators, as there are a number.
In your case, your (forward) iterator type can be simple: a T*.
Start with:
1 2 3 4 5 6 7
|
template< typename T >
class Array
{
public:
typedef T* iterator;
typedef const T* const_iterator;
};
| |
To be STL compatible, you will also need a reverse_iterator and const_reverse_iterator, both of which will require classes to implement.
Since your container is pretty much a std::vector<>, I'd look to see what vector<> does and mimic it.
Topic archived. No new replies allowed.