how to define iterators for elements of a class

let's say i have the following code :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// this code is for implementing vector in C++
template <class T>
class  Vector
{
  public:
    Vector();
    ~Vector();

    iterator begin();    // return type is iterator
    iterator end();

  private:
    unsigned int my_size;
    unsigned int my_capacity;
    T * buffer;
};

template<class T>
typename Vector<T>::iterator Vector<T>::begin()   // return_type of begin() of buffer
{
    return buffer;
}


Now, as in typename Vector<T>::iterator Vector<T>::begin(), the return type is an iterator of type Vector<T>::iterator. How should i declare/define iterator in the class Vector<T>?
The class is generic, so how will the iterator be defined?
Last edited on
For your particular implementation, you can use plain pointers as iterators instead of defining your own iterator classes. If there is a specific reason to define your own iterator classes, then I can't see it from the code you posted.
@LB this code is just a small fragment, i want to learn how to define iterators for classes.
The <iterator> header is your friend:
http://www.cplusplus.com/reference/iterator/
http://en.cppreference.com/w/cpp/header/iterator

You would derive from std::iterator<> and implement it to your needs - it does most of your work for you.
http://www.cplusplus.com/reference/iterator/iterator/
http://en.cppreference.com/w/cpp/iterator/iterator
Last edited on
Add this anywhere in your class
If you just want your container to work with range based for loops aka for (T object : vector) then you just need this:
using iterator = T*;

If you want practice writing your own iterator, do what LB has just suggested
Last edited on
@Smac89: I suggested that and he specifically requested information for making an iterator class by hand instead.
Topic archived. No new replies allowed.