创建通用堆栈 [英] Creating a generic stack

查看:80
本文介绍了创建通用堆栈的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可能有一个通用堆栈适用于所有原始和非原始数据类型?

这是一个非常严重的问题,因为这使我很困惑.看一下整数堆栈的push方法的代码

Is it possible to have a generic stack which works for all the primitive and non primitive data types?

This is a very serious question because this is confusing me a lot; look at the code of push method of the integer stack

void Stack::push(int number)
{
    Node* newNode=new Node;
    if(head==NULL)
    {
        head=newNode;
        topelement=newNode;
        current=newNode;
        head->object=number;
        head->preptr=NULL;
    }
    else
    {
        topelement=newNode;
        newNode->preptr=current;
        current=topelement;
        newNode->object=number;
    }
}


现在我的问题是,如果我们使用模板使其通用,那么它对于整数,浮点数,长整型,双精度型等都可以很好地工作,但是字符串呢?
例如,我在主程序中有一个数组,在该数组中,我从用户那里获取了字符串,然后将该数组传递给堆栈的push方法,现在看看仅为字符串编写的push方法的代码. >


Now my question is if we make it generic using templates then it can work very well for integers, floats, long, double etc, but what about strings?
For example I have an array in my main program in which I get the string from the user and after that I pass this array to the push method of the stack, now look at the code of push method written for strings only.

void stack::push(char* ptr)
{
    if(ptr==NULL)
    {
        cout<<"\n Can't be pushed";
        return;
    }
    Node* newNode=new Node;
    if(top==NULL)
    {
        head=newNode;
        current=top=newNode;
        head->preptr=NULL;
        //allocating space for the passed string
        int len;
        len=strlen(ptr);
        head->data=new char[len+1];
        strcpy(head->data,ptr);
        head->data[len]='\0';
    }
    else
    {
        top=newNode;
        newNode->preptr=current;
        current=newNode;
        int len;
        len=strlen(ptr);
        newNode->data=new char[len+1];
        strcpy(newNode->data,ptr);
        newNode->data[len]='\0';
    }
}



我需要将此方法设为通用,以便它适用于所有原始数据类型,字符串和用户定义的对象.我该怎么做?



I am required to make this method generic so that it works for all the primitive data types, strings and the user defined objects. How would I do that?

推荐答案

我将Node设为模板类,以便Data为T类型.那么您可以简单地使用Node<int>以及其他使您的船浮起的东西.然后,只需将stack设置为模板类,将ptr参数更改为T类型.在这里,您只需将newNode->data设置为ptr或它的副本.
I would make Node into a template class, so that Data is type T. Then you can simply use Node<int>, Node<char *> and whatever else floats your boat. Then, simply make stack into a template class, changing the ptr parameter to be of type T. From here, you simply set newNode->data to ptr, or a copy thereof.


您可以使用std::string代替char *.
顺便说一句,您知道C++标准库提供了stack模板类吗?
:)
You may use std::string instead of char *.
BTW Do you know C++ standard library privides a stack template class?
:)


这篇关于创建通用堆栈的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆