Reputation: 57
I am currently studying Bjarne's PPP, and I don't really understand how begin() and end() works, and how I am supposed to implement it.
Here is my code for the vector
.
template<typename T> class vector {
int sz;
T *elem;
int space;
std::allocator<T> alloc;
public:
vector():sz{0},elem{nullptr},space{0}{}
explicit vector(int s):sz{s},elem{new T[s]}, space{s}{
for(int i = 0; i<sz; i++) elem[i]=0;
}
T &at(int n);
const T &at(int n) const;
void reserve(int newalloc);
void resize(int newsize, T def=T());
int capacity() const { return space;}
void push_back(int d);
vector &operator=(const vector &a);
T *begin();
const T *begin() const;
T *end();
const T *end() const;
unsigned long size();
};
Upvotes: 2
Views: 594
Reputation: 10165
begin()
and end()
should return an iterator. Basically, iterator is a class that implements variables such as iterator_category
and value_type
, which let other functions to know how to use it.
It should also implement functions required by the iterator_category
that you choose to use.
For your a vector, you need a random access iterator. You need two classes: constant access iterator (returned by const
function) and non-constant access iterator. Usually you would derive the non-constant class from the constant class.
The positions pointed by the iterators: begin
points to the beginning of the data, and end
is begin() + size()
.
template<typename T>
class vector_iterator {
public:
typedef std::random_access_iterator_tag iterator_category;
typedef T value_type;
typedef std::ptrdiff_t difference_type;
typedef const value_type& reference;
typedef const value_type* pointer;
// Functions come here
// You must implement some operators
reference operator*() const { /* must implement */ }
vector_iterator operator+(const difference_type) const { /* must implement */ }
// Some operators can use the operations that are already implemented
vector_iterator operator-(const difference_type n) const { return *this + (-n); }
reference operator[](const difference_type n) const { return *(*this + n); }
};
Upvotes: 4