繁体   English   中英

使用模板在C ++中实现堆栈实现

[英]stack implementation in C++ using template

在下面的程序中,如何在该类的成员函数中打印堆栈数据?

#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);
}

我尝试打印数据,但是它不正确,所以我不确定如何访问堆栈元素

无需传递box& b 你可以做:

template <class T> void box<T>::display() {
    for(T& e : elems) {
        std::cout << e << std::endl;
    }
}

您可以简单地遍历“ elems”向量并打印其元素。

> template <class T> void box<T>::display() {
>     for(int i=0;i<elems.size();i++) 
>         cout<<elems[i]<<"\n";
> }

注意:
size()–返回向量中元素的数量。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM