当前位置: 代码迷 >> C语言 >> [原创]自己的库+四则运算测试
  详细解决方案

[原创]自己的库+四则运算测试

热度:640   发布时间:2008-05-10 13:06:26.0
[原创]自己的库+四则运算测试
主要为了学习数据结构,建个自己的库,日后不断更新.....
代码很垃圾,有兴趣的朋友可以试一下,bug应该不少///

/********************************************************
** Highlight software by yzfy(雨中飞燕) http://yzfy.org *
*********************************************************/
#ifndef MyDS_H_
#define MyDS_H_

#include<string>
//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
//

//  application:  to support some programing by this. The header file included
//       some basic and important ADT. For example, stack, linkStack, queue, deque
//       linkQueue, Slink, Clink, Dlink, Max(Min)Heap, BST, RBT, AVL, Splay, BTree, BHeap
//       FibHeap etc.
//
//  author:   taetrie (c) All Rights Reserved
//
//  created:  2008/5/9  
//
//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\/
class error_stack;
template<typename type>
class stack
{
public:
    //ctor and dtor
    explicit stack(int size = 50) throw();
    stack(const stack<type>& source_stack) throw();
    ~stack() throw();
    //main function
    int size() const;
    bool empty() const;
    void push(const type& value) throw(error_stack);
    void pop() throw(error_stack) ;
    const type& top() const throw(error_stack);
    //overload operator
    stack& operator=(const stack<type>& source_stack);
    template<typename type_>
    friend bool operator==(const stack<type_>& s1,const stack<type_>& s2);
    template<typename type_>
    friend bool operator> (const stack<type_>& s1,const stack<type_>& s2);
    template<typename type_>
    friend bool operator< (const stack<type_>& s1,const stack<type_>& s2);
private:
    //copy function
    void copy_(const stack<type>& source_stack);
    //data member
    type* _stack;
    int _size;
    int _top;
};
//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\/
//
// define  error_stack
class error_stack
{
public:
    explicit error_stack(const char* msg ):str(msg){}
    ~error_stack() {}
    const std::string& what() const
   
{
        return str;
    }
private:
    std::string str;
};
//\  define   stack
template<typename type>
inline int stack<type>::size() const
{
    return _size;
}
template<typename type>
inline bool stack<type>::empty() const
{
    return  -1 == _top ? true : false;
}
// copy_ function
template<typename type>
void stack<type>::copy_(const stack<type>& source_stack )
{
    for(int i = source_stack._top; i>=0; --i )
        _stack[i] = source_stack._stack[i];
}
// ctor of stack
template<typename type>
stack<type>::stack(int size) throw(): _top( -1)
{
    _stack = new type[ _size=size ];
}
template<typename type>
stack<type>::stack(const stack<type>& source_stack) throw()
{
    _stack = new type[ _size=source_stack._size ];
    if( source_stack.empty() )
    {
        _top = -1;
    }
    else
   
{
        _top = source_stack._top;
        copy_( source_stack );
    }
}
template<typename type>
stack<type>::~stack() throw()
{
    delete [] _stack;
}
// main function
template<typename type>
inline
void
stack<type>::push(const type& value) throw(error_stack)
{
    if( ++_top >= _size ) throw error_stack("OVERFLOW");
    _stack[ _top ] = value;
}
template<typename type>
inline
void
stack<type>::pop() throw(error_stack)
{
    if( empty() ) throw error_stack("DWONFLOW");
    --_top;
}
template<typename type>
inline
const
type& stack<type>::top() const throw(error_stack)
{
    if( empty() ) throw error_stack("EMPTY");
    return _stack[ _top ];
}
// overload operator
// use all of element in the stack to compare
template<typename type>
stack<type>& stack<type>::operator= (const stack<type>& source_stack)
{
    if( this != &source_stack )
    {
        delete [] _stack;
        _top = source_stack._top;  
        _stack = new type[ _size=source_stack._size ];
        copy_( source_stack );
    }
    return *this;
}
template<typename type>
bool operator== (const stack<type>& s1, const stack<type>& s2)
{
        if( s1._top == s2._top )
        {
            for(int i = s1._top; i>=0 ; --i)
            if( s1._stack[i] != s2._stack[i] ) return false;
            return true;
        }
        return false;
}
template<typename type>
inline bool operator!= (const stack<type>& s1, const stack<type>& s2)
{
    return !(s1 == s2 );
}
template<typename type>
bool operator< (const stack<type>& s1, const stack<type>& s2)
{
    if( s1._top < s2._top ) return true;
    else if( s1._top == s2._top )
    {
            for(int i=s1._top; i>=0; --i)
            if( s1._stack[i] > s2._stack[i] ) return false;
            return true;
    }
    return false;
}
template<typename type>
inline bool operator> (const stack<type>& s1, const stack<type>& s2)
{
    return  !(s1 < s2);
}
template<typename type>
inline bool operator<= (const stack<type>& s1, const stack<type>& s2)
{
    return !(s1 > s2 );
}
template<typename type>
inline bool operator>= (const stack<type>& s1, const stack<type>& s2)
{
    return !(s1 < s2 );
}
#endif


[[it] 本帖最后由 中学者 于 2008-5-10 13:09 编辑 [/it]]
搜索更多相关的解决方案: 运算  MyDS  yzfy  垃圾  兴趣  

----------------解决方案--------------------------------------------------------
确实有bug....
四则运算部分:
Dev C++通过测试,由于VC6.0对模板和异常和友元的支持有问题,所以没测试..
/********************************************************
** Highlight software by yzfy(雨中飞燕) http://yzfy.org *
*********************************************************/
#include <cstdlib>
#include <iostream>
#include <string>
#include<exception>
#include"MyDS.h"
using namespace std;
class illege{};

class Calculate
{
public:
    Calculate(int c_size=50,int d_size=50)
    :char_stack(c_size),double_stack(d_size){}
   
    static Calculate& GetObj() { return _c;}
    // OrderFix convert PostFix
    friend void OrderToPost(const string&,Calculate& );
    // output number
    friend void OutPutNum(double,Calculate& );
    // Get value
    double GetValue() const { return double_stack.top(); }
private:
    void _calculate(char ch,double v1,double v2) ;
    static Calculate _c;
    stack<char> char_stack;
    stack<double> double_stack;
};
Calculate Calculate::_c;

void Calculate::_calculate(char ch,double v1,double v2)
{
    switch(ch)
    {
    case '+': v1 = v1+v2; break;
    case '-': v1 = v1-v2; break;
    case '*': v1 = v1*v2; break;
    case '/':
        if( v2== 0 ) throw illege();
        v1 = v1/v2;
        break;
    }
    double_stack.pop();
    double_stack.push(v1);
}
// prority of comparision
int GetPro(char ch);  
// creat unexception
void my_unexception()
{
    cerr<<"The programing will be exit because of some unknown causes..."
        
<<endl;
    exit(0);
}
int main(int argc, char *argv[])
{
    set_unexpected(my_unexception);
    try
   
{
        string buf;
        while(cin>>buf)
        {
            cout<<"OrderFix expression:  "<<buf<<endl;
            cout<<"PostFix expression:  ";
            OrderToPost(buf,Calculate::GetObj());
            cout<<"The result of this expression: "
               
<<Calculate::GetObj().GetValue()<<endl;
        }

    }
    catch(error_stack& e)
    {
        if(e.what()=="OVERFLOW") cerr<<"Stack is overflow!It will be aborted."<<endl;
        else if(e.what()=="DWONFLOW") cerr<<"Stack is dwonflow!It will be aborted."<<endl;
        else if(e.what()=="EMTPY")
        cerr<<"Stack is so empty that you don't get element at the  top of the stack!"<<endl;
    }
    catch(illege& )
    {
        cerr<<"Using operator is illege!It will be aborted!"<<endl;
    }
    system("PAUSE");
    return EXIT_SUCCESS;
}
void OrderToPost(const string& buf,Calculate& C)
{
    int l = buf.length();
    if( buf[l-1]!=')'&&(buf[l-1]<48||buf[l-1]>57)) throw illege();
    double n=0;
    for(int i=0; buf[i]!='\0'; )
    {
        if( 48<=buf[i]&&buf[i]<=57 )  
        {
            n = n*10+buf[i++]-'0';
        }
        else if( buf[i]=='.' ) // do with double
        {
            if( buf[i-1]<48&&buf[i-1]>57 )  //  it isn't number
                throw illege();
            // else
            ++i;  for(; buf[i]>=48&&buf[i]<=57;++i )  n += (double)(buf[i]-'0')/10;
        }
        else if( buf[i]=='(' )
        {
            if( n!=0 )   // do with brief expression
            {
                OutPutNum(n,C); n=0;
                C.char_stack.push('*');
            }
                C.char_stack.push(buf[i++]);
        }
        else if( buf[i]==')' )
        {
            OutPutNum(n,C);
            //output all of the element in char_stack
            for(;!C.char_stack.empty()&&C.char_stack.top()!='('; )
            {
                n=C.double_stack.top();
                C.double_stack.pop();
                C._calculate(C.char_stack.top(),C.double_stack.top(),n);
                cout<<C.char_stack.top();
                C.char_stack.pop();
            }
            n=0;
            C.char_stack.pop();
            ++i;
        }
        else if( buf[i]=='+'||buf[i]=='-'
               
||buf[i]=='*'||buf[i]=='/')
        {
                // operator is illege
            if( buf[i-1]=='+'||buf[i-1]=='-'
               
||buf[i-1]=='*'||buf[i-1]=='/')  throw illege();
                // output number
                OutPutNum(n,C);
               
                if( !C.char_stack.empty()&&
                    C.char_stack.top() !='('&&
                GetPro(buf[i])<=GetPro(C.char_stack.top()) )
                {
                n=C.double_stack.top();
                C.double_stack.pop();
                C._calculate(C.char_stack.top(),C.double_stack.top(),n);
                cout<<C.char_stack.top();
                C.char_stack.pop();
                }
                C.char_stack.push(buf[i++]);
                n=0;
        }
        else throw illege();
        }

        for(; !C.char_stack.empty(); )
        {
        OutPutNum(n,C);
        n=C.double_stack.top();
        C.double_stack.pop();
        C._calculate(C.char_stack.top(),C.double_stack.top(),n);
        cout<<C.char_stack.top();
        C.char_stack.pop();
        n=0;
        }
        cout<<endl;
}
int GetPro(char ch)
{
    switch(ch)
    {
    case '*': return 2;
    case '/': return 2;
    case '+': return 1;
    case '-': return 1;
    }
    return 0;
}
void OutPutNum(double n,Calculate& C)
{
    if( n!= 0)
    {
        cout<<" "<<n;
        C.double_stack.push(n);
    }
}


[[it] 本帖最后由 中学者 于 2008-5-10 13:13 编辑 [/it]]
----------------解决方案--------------------------------------------------------
顶一个。。。。。。。

[color=white]
----------------解决方案--------------------------------------------------------
顶……
代码看起来好吓人,没有飞燕的清爽,所以就没有看了……尽管肯定比飞燕的好懂很多……
----------------解决方案--------------------------------------------------------
楼上的是什么意思嘛。。。。

[color=white]
----------------解决方案--------------------------------------------------------
别逼我发我的四则运算代码。。。。

[color=white]
----------------解决方案--------------------------------------------------------
4#楼在表扬你...美女杀伤力就是大啊..呵呵..中学兄弟挺你..不过好像最近也没办法有大段时间看东西了[tk01

[[it] 本帖最后由 sunkaidong 于 2008-5-10 14:30 编辑 [/it]]
----------------解决方案--------------------------------------------------------
燕子的代码看得懂是享受,看不懂是难受.........///
----------------解决方案--------------------------------------------------------
偶的四则代码比较垃圾的说。。。。

[color=white]
----------------解决方案--------------------------------------------------------