STL template&Container--how to change normal function into generic function.

Q:    
    Below is usual way we find one element in an array:
    in this case we have to bear the knowledge of value type"int",the size of array,even the existence of an array. would you re-write it using template to eliminate all these dependenciies? (SAP 2004)
    const int *find1(const int *array,int n,int x)
    {
    const int *p=array;
    for(int i=0;i<n;i++)
    if(*p==x)
            return p;
    ++p;
    }
        return 0;

A:
    template<typename T>
    const T * find(T *array,T n,T x)
{
    const *T=array;
    int i;
    for(i=0;i<n;i++)
    {
    if(*p==x)
    return p;
    ++p;
    }
    return 0;


 

魔板类实现链表sample:

#include "stdlib.h"

template <class T>

class list

{

public :

         list()

         {

                 this->m_pFirst=this->m_pTail=NULL;

         }

         ~list()

         {

                   printf("deconts");

         }

typedef struct node

{

struct node *link;

T data;

}NODE;

         void InsertNode(T data);

         void DeleteNode(T data);

         void Sort();

         void show();

private:

         NODE *m_pFirst;

         NODE *m_pTail;

};

template<class T>

void list<T>::show()

{

         NODE *p=this->m_pFirst;

                   while(p!=NULL)

                   {

                            printf("%d ",p->data);

                            p=p->link;

                   }

}

template <class T>

void list<T>::InsertNode(T data)

{

         NODE *newNode=(NODE *)malloc(sizeof(NODE));

         newNode->data=data;

         newNode->link=NULL;

         if(this->m_pFirst==NULL)

                   m_pFirst=this->m_pTail=newNode;

         else

         {

                   this->m_pTail->link=newNode;

                   this->m_pTail=newNode;

         }

        

}

template <class T>

void list<T>::Sort()

{

         NODE *p;

         for(p=this->m_pFirst ;p!=NULL;p=p->link)

         {

                   NODE *q;

                   NODE *k=NULL;

                   for(q=p->link;q!=NULL;q=q->link)

                            if (p->data< q->data)

                                      k=q;

                   int x;

                   if(k!=NULL)

                   {

                   x=p->data;

                   p->data=k->data;

                   k->data=x;

                   }

         }

}

posted on 2008-02-26 09:45  飞天舞者  阅读(265)  评论(0编辑  收藏  举报

导航

For more information about me, feel free email to me winston.he@hotmail.com