Templates and Collection Classes

本文介绍使用模板实现集合类的方法,特别关注微软基础类库中使用的六种集合类,并提供了一个简单的栈类实现示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 
Templates are a good way of implementing collection classes. Version 4.0 and later of the Microsoft Foundation Class Library uses templates to implement six collection classes: CArray, CMap, CList, CTypedPtrArray, CTypedPtrList, and CTypedPtrMap. For additional information on using and customizing these classes, see Collections Topics.

The MyStack collection is a simple implementation of a stack. The two template parameters, T and i, specify the type of elements in the stack and the maximum number of that item in the stack. The push and pop member functions add and remove items on the stack, with the stack growing from the bottom.

// templates_and_collection_classes.cpp
template <class T, int i> class MyStack
{
   T StackBuffer[i];
   int cItems;
public:
   MyStack( void ) : cItems( i )
   {
   };
   void push( const T item );
   T pop( void );
};

template <class T, int i> void MyStack< T, i >::push( const T item )
{
   if( cItems > 0 )
      StackBuffer[--cItems] = item;
   else
      throw "Stack overflow error.";
}

template <class T, int i> T MyStack< T, i >::pop( void )
{
   if( cItems < i )
      return StackBuffer[cItems++]
   else
      throw "Stack underflow error.";
}

int main()
{
   MyStack<char , 1> v;
   v.push('a');
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值