0

I am very new to C++ and am trying to create a "Generic Class" that can take any input.

I need a way to store whatever input my class receives in either an Array or a Vector. I am however struggling to figure out how to do that.

I tried to do this in my .cpp File:

template<typename T> T data[5];
template<typename T> vector<T> vect;

This is what my Header File looks like:

#include <vector>

using namespace std;

template <class T> class Stack {

public:

    void push(T x);

    T peek();
    T pop();

    int size();
    bool contains();


private:

    vector<T> data;

};

But that is obviously not working, I am given to understand that what I am doing is not possible? How would I be able to create an Array or Vector that can store whatever my class receives?

I am quite new to this, so apologize for silly mistakes and or misunderstandings.

Richard
  • 457
  • 1
  • 6
  • 21
  • You already have a vector in the class, there's no need for any other. Just implement the member functions to interact with that. In the header, not a source file, because http://stackoverflow.com/questions/495021. – Mike Seymour May 28 '15 at 16:03
  • **don't put `using namespace std;` in a header file**. Your .cpp file doesn't actually use the `Stack` class so I'm not sure how you're trying to connect the two? – Ryan Haining May 28 '15 at 16:04
  • @ Ryan Haining, sorry I meant the .cpp File is the Stack.cpp, I posted the Stack.h file. – Richard May 28 '15 at 16:14
  • @Mike Seymour, Thanks for the comment, so I basically declare the vector in the header, and interact with it using methods? – Richard May 28 '15 at 16:22
  • @Richard: Yes, that's how a class works. You've already got the declarations, just implement the functions. – Mike Seymour May 28 '15 at 16:23

1 Answers1

2

Try this. I have used vector here to store the data. Store this in a .cpp file and compile and execute.

You had those function declaration. You will get the function bodies here.

#include<iostream>
#include<vector>
using namespace std;

template <class T>
class Stack{
private:
    vector<T> elems;
public:
    void push(T);
    T pop();
    T peek(); 
};

template<class T>
void Stack<T>:: push(T obj){
    elems.push_back(obj);
}

template<class T>
T Stack<T>::pop(){
    if(!elems.empty()){
        T temp = elems.back();
        elems.pop_back();
        return temp;
    }
}

template<class T>
T Stack<T>::peek(){
    if(!elems.empty())
        return elems.back();
}

int main(){
    Stack<float> S;
    S.push(5.42);
    S.push(3.123);
    S.push(7.1);
    cout << S.pop() << endl;
    S.pop();
    cout << S.peek() << endl;
    return 0;
}

Output

7.1
5.42
Surajeet Bharati
  • 1,363
  • 1
  • 18
  • 36