Create a simple templatized vector class - C++ template

C++ examples for template:template class

Description

Create a simple templatized vector class

Demo Code

#include <string>
#include <cstdlib>
#include <cstdio>
#include <iostream>
template <class T>
class MyVector{/* w w w.  j  a v  a 2 s .  c o  m*/
 public:
    MyVector(int nArraySize)
    {
        // store off the number of elements
        nSize = nArraySize;
        array = new T[nArraySize];
        reset();
    }
    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;
};


using namespace std;

class Name
{
  public:
    Name() = default;
    Name(string s) : name(s) {}
    const string& display() { return name; }
  protected:
    string name;
};

int main(int argc, char* pArgs[])
{

    MyVector<int> integers(10);

    integers.add(1);
    integers.add(2);
    integers.add(3);
    integers.add(4);

    cout << "\nHere are the numbers you entered:" << endl;
    for(int i = 0; i < integers.size(); i++)
    {
        cout << i << ":" << integers.get() << endl;
    }



    // create a vector of Name objects
    MyVector<Name> names(20);

    names.add(Name("a"));
    names.add(Name("b"));
    names.add(Name("c"));


    cout << "\nHere are the names you entered" << endl;
    for(int i = 0; i < names.size(); i++)
    {
        Name& name = names.get();
        cout << i << ":" << name.display() << endl;
    }


    return 0;
}

Result


Related Tutorials