Reputation: 91
In below program how can I print stack data in the member function of that class?
#include <iostream>
#include <vector>
using namespace std;
template <class T>
class box{
public :
vector<T> elems;
void push(T); // pushing data into stack
void pop();
void display(); // displaying the stack data
};
template <class T> void box<T> :: push(T ele)
{
elems.push_back(ele); // pushing stack elements
}
template <class T> void box<T> :: pop(void)
{
elems.pop_back();
}
template <class T> void box<T> :: display(box &b)
{
//How to display the data inserted in stack here??
}
int main(void)
{
box<int> b;
b.push(3); // inserting stack data into template
b.push(4);
b.push(5);
b.push(6);
b.push(7);
}
I tried to print the data but it was not proper, so I am not sure how can I access the stack elements
Upvotes: 0
Views: 2613
Reputation: 41
You can simply iterate through the "elems" vector and print its elements.
> template <class T> void box<T>::display() {
> for(int i=0;i<elems.size();i++)
> cout<<elems[i]<<"\n";
> }
NOTE:
size() – Returns the number of elements in the vector.
Upvotes: 0
Reputation: 2576
No need to pass a box& b
. You can do:
template <class T> void box<T>::display() {
for(T& e : elems) {
std::cout << e << std::endl;
}
}
Upvotes: 2