Monday, June 13, 2011

C++: Building custom vector class.


Making custom container class with iterator would be a good example for C++ beginner.




Vector.h


#ifndef VECTOR_H
#define VECTOR_H

#include <vector>
#include "VectorIterator.h"

class Vector {
public:
    typedef VectorIterator iterator;

    Vector(int size) { data_.resize(size); }

    int size() const;
    void push_back(const int val);

    VectorIterator begin();
    VectorIterator end();

    int& operator[](const int& idx);
private:
    std::vector<int> data_;
};

inline int &
Vector::operator[](const int& idx) {
    return data_[idx];
}
inline int
Vector::size() const {
    return data_.size();
}

inline void
Vector::push_back(const int val) {
    data_.push_back(val);
    return;
}

#endif /* VECTOR_H */


Vector.cpp


#include "Vector.h"

VectorIterator
Vector::begin() {
    return VectorIterator(&data_);
}

VectorIterator
Vector::end() {
    VectorIterator vec(&data_);
    vec.setIndex(data_.size());
    return vec;
}


VectorIterator.h


#ifndef VECTORITERATOR_H
#define VECTORITERATOR_H

#include <vector>

class VectorIterator {
public:

    VectorIterator();
    VectorIterator(std::vector<int> * data);

    void setIndex(int v);
    int operator*();
    int operator++();
    bool operator==(const VectorIterator& rhs) const;
    bool operator!=(const VectorIterator& rhs) const;
private:
    std::vector<int>* pvec_;
    int index_;
};

inline int
VectorIterator::operator*()
{
    return (*pvec_)[index_];
}

inline int
VectorIterator::operator++()
{
    index_++;
    return (*pvec_)[index_];
}

inline bool
VectorIterator::operator==(const VectorIterator& rhs) const
{
    return (pvec_ == rhs.pvec_ && index_ == rhs.index_);
}

inline bool
VectorIterator::operator!=(const VectorIterator& rhs) const
{
    return !(*this == rhs);
}
#endif /* VECTORITERATOR_H */


VectorIterator.cpp


#include "VectorIterator.h"

void
VectorIterator::setIndex(int v) {
    index_ = v;
    return;
}

VectorIterator::VectorIterator()
    : pvec_(NULL), index_(0) {}

VectorIterator::VectorIterator(std::vector<int> * data)
    : pvec_(data), index_(0) {}



main.cpp


#include <iostream>
#include "Vector.h"

int main()
{
    int size = 10;
    Vector vec(size);

    for (int i = 0; i < vec.size(); i++)
        vec[i] = 2 * i;

    for (Vector::iterator iter = vec.begin();
        iter != vec.end(); ++iter)
        std::cout << *iter << std::endl;

    return 0;
}

No comments:

Post a Comment