homework 15 2016 6 2 模板

Posted 任我主宰

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了homework 15 2016 6 2 模板相关的知识,希望对你有一定的参考价值。

#include<iostream>
#include<cmath>
#include<cstdio>
using namespace std;

template <typename T, int capacity>

class Array

{
  public:     
    Array(); 
    ~Array();
    bool empty();
    void push(T value);
    T pop();
    int size();
    T& operator[] (int index);

private:
    T* elements; 
    int num;
};


class ArrayException

{

  public: 
       ArrayException(const char *msg);
       const char *what() const;
  private:
       const char *message;
};

 

 

 

 

 

template <typename T, int capacity>
Array<T,capacity>::Array(){
 num = 0;
    elements = new T[capacity];

template <typename T, int capacity>                     
Array<T,capacity>::~Array(){
    delete [] elements;
}

template <typename T, int capacity>                  
bool Array<T,capacity>::empty(){
    if(num==0) return true;
    else return false;
}   

template <typename T, int capacity>
void Array<T,capacity>::push(T value){
    if(num >= capacity) throw ArrayException("Array Full Exception");
    else {
        elements[num] = value;
        num++;
    }
}

template <typename T, int capacity>
T Array<T,capacity>::pop(){
    if(num == 0) throw ArrayException("Array Empty Exception");
    else {
        T temp = elements[num-1];
        elements[num-1] = 0;
        num--;
        return temp;
    }
}


template <typename T, int capacity>
int Array<T,capacity>::size(){
 return num;
}

template <typename T, int capacity>
T& Array<T,capacity>::operator[] (int index){
    if(index < 0 || index >= num) throw ArrayException("Out of Range Exception");
    else return elements[index];
}

ArrayException::ArrayException(const char *msg){
 message=msg;
}

const char* ArrayException::what() const{
    return message;
 
}

 


void test()
{
Array<int,1> intArray;


try {
    intArray.push(1);
}

catch (ArrayException ex) {
     cout << ex.what() << endl;
}

try {

     cout << intArray[3] << endl;

}

catch (ArrayException ex) {

     cout << ex.what() << endl;

}

try {

     cout << intArray.pop() << endl;

}

catch (ArrayException ex) {

    cout << ex.what() << endl;
}

}
int main(){
 
 
    Array<int,15> a;
 for (int i = 0; i <15; i++) a.push(i);
 cout<<"a.size=="<<a.size()<<endl;
 cout<<"a[0]=="<<a[0]<<endl;
 cout<<"a[a.size()-1]=="<<a[a.size()-1]<<endl;
 cout<<"a[-1]=="<<a[-1]<<endl;
 cout<<"a[a.size()]=="<<a[a.size()]<<endl;

 cout << endl;
 
 return 0;
 
}

以上是关于homework 15 2016 6 2 模板的主要内容,如果未能解决你的问题,请参考以下文章

SoftwareTest homework3

[2016-03-28][HDU][1074][Doing Homework]

Homework

C 语言 homework

0926-----homework(4,5,6)

hdu 1074 Doing Homework(状压)