Search code examples
c++classvectortemplate-classes

Is it possible to use inside a template class, a vector of class stack elements?


I have a "stack.h" and a "stack.cpp" file that define a hand-made stack class.

What i want to do now, is to create another class "name" that has in it's composition a vector of "nr" stacks and i'm not sure where to start.

depou.h:

#pragma once
#include <vector>
#include "stiva.h"

template <class T>
class depou {
private:
    int nr;
    std::vector<stiva<T> > depouArray;

public:
    depou (int x, int lungTren);
};

template <class T>
depou<T>::depou (int x, int lungTren){
    int i;
    nr = x;
    depouArray = new std::vector<stiva<T> > (nr);
/*  for (i=0; i<nr; i++){
        depouArray[i] = stiva<T> (lungTren);
    } this is incorrect */
}

My name.h doesn't compile i just want to know if it's possible to do a vector of that kind.

My stack header is called "stiva", so i edited the "name.h" file according so.

stiva.h

#pragma once

template <class T>
class stiva {
private:
    int top;
    int size;
    T *stackArray;

public:
    stiva();
    stiva (int s);
    ~stiva (){ delete [] stackArray; }
    int push (const T&);
    int pop (T&);
  int topElem (T&);
    int isEmpty (){return top == -1;}
    int isFull () {return top == size -1;}
    int search (T x);
    void setSize (const int& sz){
        size=sz;
    }
};

template <class T>
stiva<T>::stiva (){
    size = 10;
    top = -1;
    stackArray = new T[size];
}

template <class T>
stiva<T>::stiva (int s){
    size = s>0 && s<1000? s : 10;
    top = -1;
    stackArray = new T[size];
}

template <class T>
int stiva<T>::push (const T& x){
    if (!isFull()){
        stackArray[++top] = x;
        return 1;
    }
    else{
        size *= 2;
        stackArray = (T*) realloc (stackArray, 2*size * sizeof(T));
        stackArray[++top] = x;
        return 1;
    }
    return 0;
}

template <class T>
int stiva<T>::pop (T& popValue){
    if (!isEmpty ()){
        popValue = stackArray[top--];
        return 1;
    }
    return 0;
}

template <class T>
int stiva<T>::topElem (T& topValue){
    if (!isEmpty ()){
        topValue = stackArray[top];
        return 1;
    }
    return 0;
}

in main i initialize like this:

depou d(5,10);


Solution

  • You can initialize the vector to your given size in the member intializer of the constructor:

    template <class T>
    class name {
    private:
        int nr;
        std::vector<stack<T> > nameArray;
    
    public:
        name (int x) : nr(x), nameArray(nr) {}
        //other methods
    };
    

    Working example here: http://codepad.org/ZT9iuQEg