C++基础语法:类模板(容器)定义的内容

前言

       "打牢基础,万事不愁" .C++的基础语法的学习

引入

        类模板是泛型编程的重要组成部分,通常用来实现数据结构,做成容器类.从几个现成容器探寻类模板定义的内容.引用了参考书<C++ Prime Plus> 6th Edition(以下称"本书")的几个例子:数组栈,指针栈,链队列

类模板回顾

        类模板把数据类型---class类型或基本类型作为参数传入,设类型为T,则可以把T*(指针),T**(双重指针), T a[](数组)作为类模板属性.(自用)关于程序的一些概念4:C++泛型初探-优快云博客

         类模板的类名和普通class类相同,构造函数形式和普通class类也相同.在类模板对象使用时,要类名后加上"<具体类型名>",在定义类模板方法时,要在类名后加上"<形参类型名>"

  数组栈 

        本书P569,复制书中stacktp.h代码如下:

// stacktp.h -- a stack template
#ifndef STACKTP_H_
#define STACKTP_H_
template <class Type>
class Stack
{
private:
    enum {MAX = 10};    // constant specific to class
    Type items[MAX];    // holds stack items
    int top;            // index for top stack item
public:
    Stack();
    bool isempty();
    bool isfull();
    bool push(const Type & item); // add item to stack
    bool pop(Type & item);        // pop top into item
};

template <class Type>
Stack<Type>::Stack()
{
    top = 0;
}

template <class Type>
bool Stack<Type>::isempty()
{
    return top == 0;
}

template <class Type>
bool Stack<Type>::isfull()
{
    return top == MAX;
}

template <class Type>
bool Stack<Type>::push(const Type & item)
{
    if (top < MAX)
    {
        items[top++] = item;
        return true;
    }
    else
        return false;
}

template <class Type>
bool Stack<Type>::pop(Type & item)
{
    if (top > 0)
    {
        item = items[--top];
        return true;
    }
    else
        return false; 
}

#endif

 数据部分:

private:
    enum {MAX = 10};    // constant specific to class
    Type items[MAX];    // holds stack items
    int top;            // index for top stack item

 其中:items[MAX]是物理容器,必须存在的.MAX是数组长度;top表示当前数组元素个数,同时也是指针,可以获得最后的那个元素items[--top].top值比数组索引值多1.添加第一个元素后,数组里有元素items[0],此时top等于1,依次类推.

初始化:建立数组,把当前元素个数top设为0.

算法:入栈和出栈

指针栈

本书P574,复制代码stcktp1.h,如下: 

// stcktp1.h -- modified Stack template
#ifndef ST
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

重庆彭枫

你的鼓励是我创作的动力,谢谢

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值