StackWithMinTesting1007.cpp

来源:互联网 发布:java怎么学 编辑:程序博客网 时间:2024/06/12 21:55
// StackWithMinTesting1007.cpp : 定义控制台应用程序的入口点。
//


#include "stdafx.h"
#include <deque>
#include <assert.h>
#include<iostream>
#include<vector>
using namespace std;




template <typename T> class StackWithMin
{
public:
      StackWithMin(void) {};
      virtual ~StackWithMin(void) {};
      T& top(void);
      const T& top(void) const;
      void push(const T& value);
      void pop(void);
      const T& min(void) const;


private:
     T m_data;               // the elements of stack
     T m_minIndex;      // the indices of minimum elements
};


template<typename T>T& StackWithMin<T>::top()
{
return m_data.back();
}
template<typename T>const T& StackWithMin<T>::top() const
{
return m_data.back();
}




template<typename T> void StackWithMin<T>::push(const T& value)
{
m_data.push_back(value);
if(m_minIndex.size()==0)
m_minIndex.push_back(0);
else
{
if(value<m_minIndex.back())
m_minIndex.push_back(value);
else
m_minIndex.push_back(m_minIndex.back());
}
}


template<typename T> void StackWithMin<T>::pop(void )
{
m_data.pop_back();
m_minIndex.pop_back();
}


template<typename T>const T& StackWithMin<T>::min(void)const
{
assert(m_minIndex.size()>0);


return m_minIndex.back();
}


int main()//如果这个模版程序在vector的参数没有隐式转换  而是explicite的  那怎么解决?
{
class StackWithMin<deque<int> > mystack;
mystack.push(9);
mystack.push(10);
mystack.push(5);
mystack.push(6);
mystack.push(1);
mystack.push(2);


return 0;
}
原创粉丝点击