[英]stack implementation in C++ using template
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 我尝试打印数据,但是它不正确,所以我不确定如何访问堆栈元素
No need to pass a box& b
. 无需传递box& b
。 You can do: 你可以做:
template <class T> void box<T>::display() {
for(T& e : elems) {
std::cout << e << std::endl;
}
}
You can simply iterate through the "elems" vector and print its elements. 您可以简单地遍历“ elems”向量并打印其元素。
> 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. size()–返回向量中元素的数量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.