一個簡單的cpp list

list.h

#ifndef _list_h_

#define _list_h_
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
using namespace std;


void Exception(int _condition, const char* _error_msg);


template<class type>
class list
{
public:
  list(int _size){
    this->_p = new type[_size];
    this->_maxsize = _size;
    this->_size = 0;
  }


  ~list(){
    if(_p){
      delete []_p;
      _p = nullptr;
    }
  }


  int list_size(){ return this->_size;}
  int list_empty(){ return !this->_size;}
  int list_find(type& _item) const;
  type list_get_data(int _pos) const {
    if(_pos <0 || _pos >this->_size){
      Exception(1, "Out of position");
    }
    return this->_p[_pos];
  }
  void list_insert(const type& _item){
    Exception(this->_size >= this->_maxsize,"Out of position");
    this->_p[this->_size++] = _item;
  }
  bool list_delete(const type& _item);
  void list_clear(){
    this->_size = 0;
  }
protected:
  int _size;
  int _maxsize;
  type* _p;
};


#endif // _list_h_




list.cpp

#include "list.h"


void Exception(int _condition, const char* _error_msg)
{
  if(_condition){
    cerr<<_error_msg<<endl;
    exit(0);
  }
}


template <class type>
int list<type>::list_find(type& _item) const
{
  int j=0;
  for(; j<=this->_size-1 && this->_p[j]!= _item; j++) ;
  if(j > this->_size -1) return -1;
  return j;
}


template <class type>
bool list<type>::list_delete(const type& _item)
{
  int j = list_find(_item);
  if(j >= 0){
    for(int k=j+1; j<=this->_size -1; j++)
      this->_p[k-1] = this->_p[k];
    this->_size--;
    return 1;
  }
  return 0;
}




orderlist.h


#ifndef _orderlist_h_
#define _orderlist_h_
//通過繼承使用上面的類
#include "list.h"
template<class type>
class orderlist : public list<type>
{
public:
  orderlist(int _size): list<type>(_size){}//直接初始化父類
  void list_insert(const type& _item);
};


template <class type>
void orderlist<type>::list_insert(const type& _item)
{
  int k , j;
  Exception(this->_size >= this->_maxsize,"Out of position");
  for(k=0; k<=this->_size-1 && _item>this->_p[k]; k++); //首先找打比當前值小的位置


  for(j=this->_size-1; j>=k; j--)
    this->_p[j+1] = this->_p[j];


  this->_p[k] = _item;
  this->_size++;
  return ;
}
#endif


main.cpp

#include <iostream>
#include "orderlist.h"
using namespace std;


int main()
{
    //list<int>* p_list = new list<int>(100);//需要指定對應的數據類型


    orderlist<int>* p_list = new orderlist<int>(100);//需要指定對應的數據類型
    for(int i=99; i>=0; i--)
      p_list->list_insert(i + 1);
    cout<<p_list->list_size()<<endl;
    for(int i=0; i<100; i++)
      cout<<p_list->list_get_data(i)<<endl;


    p_list->list_clear();
    delete p_list;
    return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章