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

问题描述

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

这是一个非常严重的问题,因为这使我很困惑.看一下整数堆栈的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?

推荐答案



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

08-19 08:17