C++ Class template create generic vector

Description

C++ Class template create generic vector


#include <cstdlib>
#include <cstdio>
#include <iostream>
#include <initializer_list>
using namespace std;


template <class T>
class MyVector// ww  w .  j  av a 2  s.c  o  m
{
  public:
    MyVector(int nArraySize)
    {
        nSize = nArraySize;
        array = new T[nArraySize];
        reset();
    }
    MyVector(const std::initializer_list<T> il) :MyVector(il.size())
    {
        // copy the contents of il into the vector
        for(const T* p = il.begin(); p < il.end(); p++)
        {
            add(*p);
        }
    }

    int size() { return nWriteIndex; }
    void reset() { nWriteIndex = 0; nReadIndex = 0; }
    void add(const T& object)
    {
        if (nWriteIndex < nSize)
        {
            array[nWriteIndex++] = object;
        }
    }
    T& get()
    {
        return array[nReadIndex++];
    }

  protected:
    int nSize;
    int nWriteIndex;
    int nReadIndex;
    T* array;
};

int main(int argc, char* pArgs[])
{
    MyVector<int> myVector = {10, 20, 30, 40, 50};

    for(int i = 0; i < myVector.size(); i++)
    {
        cout << i << " : " << myVector.get() << "\n";
    }

    return 0;
}



PreviousNext

Related