// std_lib_facilities.h/*
simple "Programming: Principles and Practice using C++ (second edition)" course header to
be used for the first few weeks.
It provides the most common standard headers (in the global namespace)
and minimal exception/error support.
Students: please don't try to understand the details of headers just yet.
All will be explained. This header is primarily used so that you don't have
to understand every concept all at once.
By Chapter 10, you don't need this file and after Chapter 21, you'll understand it
Revised April 25, 2010: simple_error() added
Revised November 25 2013: remove support for pre-C++11 compilers, use C++11: <chrono>
Revised November 28 2013: add a few container algorithms
Revised June 8 2014: added #ifndef to workaround Microsoft C++11 weakness
*/#ifndef H112#define H112 251113L#include<iostream>#include<iomanip>#include<fstream>#include<sstream>#include<cmath>#include<cstdlib>#include<string>#include<list>#include<forward_list>#include<vector>#include<unordered_map>#include<algorithm>#include<array>#include<regex>#include<random>#include<stdexcept>//------------------------------------------------------------------------------//------------------------------------------------------------------------------typedeflong Unicode;//------------------------------------------------------------------------------usingnamespace std;template<classT> string to_string(const T& t){
ostringstream os;
os << t;return os.str();}struct Range_error : out_of_range {// enhanced vector range error reportingint index;Range_error(int i):out_of_range("Range error: "+to_string(i)),index(i){}};// trivially range-checked vector (no iterator checking):template<classT>struct Vector :public std::vector<T>{using size_type =typename std::vector<T>::size_type;#ifdef _MSC_VER// microsoft doesn't yet support C++11 inheriting constructorsVector(){}explicitVector(size_type n):std::vector<T>(n){}Vector(size_type n,const T& v):std::vector<T>(n, v){}template<classI>Vector(I first, I last): std::vector<T>(first, last){}Vector(initializer_list<T> list): std::vector<T>(list){}#elseusing std::vector<T>::vector;// inheriting constructor#endif
T&operator[](unsignedint i)// rather than return at(i);{if(i<0||this->size()<= i)throwRange_error(i);return std::vector<T>::operator[](i);}const T&operator[](unsignedint i)const{if(i<0||this->size()<= i)throwRange_error(i);return std::vector<T>::operator[](i);}};// disgusting macro hack to get a range checked vector:#define vector Vector// trivially range-checked string (no iterator checking):struct String : std::string {using size_type = std::string::size_type;// using string::string;char&operator[](unsignedint i)// rather than return at(i);{if(i<0||size()<= i)throwRange_error(i);return std::string::operator[](i);}constchar&operator[](unsignedint i)const{if(i<0||size()<= i)throwRange_error(i);return std::string::operator[](i);}};namespace std {template<>struct hash<String>{
size_t operator()(const String& s)const{return hash<std::string>()(s);}};}// of namespace stdstruct Exit : runtime_error {Exit():runtime_error("Exit"){}};// error() simply disguises throws:inlinevoiderror(const string& s){throwruntime_error(s);}inlinevoiderror(const string& s,const string& s2){error(s + s2);}inlinevoiderror(const string& s,int i){
ostringstream os;
os << s <<": "<< i;error(os.str());}template<classT>char*as_bytes(T& i)// needed for binary I/O{void* addr =&i;// get the address of the first byte// of memory used to store the objectreturnstatic_cast<char*>(addr);// treat that memory as bytes}inlinevoidkeep_window_open(){
cin.clear();
cout <<"Please enter a character to exit\n";char ch;
cin >> ch;return;}inlinevoidkeep_window_open(string s){if(s =="")return;
cin.clear();
cin.ignore(120,'\n');for(;;){
cout <<"Please enter "<< s <<" to exit\n";
string ss;while(cin >> ss && ss != s)
cout <<"Please enter "<< s <<" to exit\n";return;}}// error function to be used (only) until error() is introduced in Chapter 5:inlinevoidsimple_error(string s)// write ``error: s and exit program{
cerr <<"error: "<< s <<'\n';keep_window_open();// for some Windows environmentsexit(1);}// make std::min() and std::max() accessible on systems with antisocial macros:#undef min#undef max// run-time checked narrowing cast (type conversion). See ???.template<classR,classA> R narrow_cast(const A& a){
R r =R(a);if(A(r)!= a)error(string("info loss"));return r;}// random number generators. See 24.7.inlineintrandint(int min,int max){static default_random_engine ran;return uniform_int_distribution<>{min, max}(ran);}inlineintrandint(int max){returnrandint(0, max);}//inline double sqrt(int x) { return sqrt(double(x)); } // to match C++0x// container algorithms. See 21.9.template<typename C>using Value_type =typename C::value_type;template<typename C>using Iterator =typename C::iterator;template<typename C>// requires Container<C>()voidsort(C& c){
std::sort(c.begin(), c.end());}template<typename C,typename Pred>// requires Container<C>() && Binary_Predicate<Value_type<C>>()voidsort(C& c, Pred p){
std::sort(c.begin(), c.end(), p);}template<typename C,typename Val>// requires Container<C>() && Equality_comparable<C,Val>()
Iterator<C>find(C& c, Val v){return std::find(c.begin(), c.end(), v);}template<typename C,typename Pred>// requires Container<C>() && Predicate<Pred,Value_type<C>>()
Iterator<C>find_if(C& c, Pred p){return std::find_if(c.begin(), c.end(), p);}#endif
#include"std_lib_facilities.h"doubleprimary();doubleterm();doubleexpression();classToken{public:char kind;double value;Token(char ch):kind(ch),value(0){}Token(char ch,double val):kind(ch),value(val){}};
Token get_token();
vector<Token>tok;classToken_stream{public:Token_stream();
Token get();voidputback(Token t);private:bool full;
Token buffer;};
Token_stream::Token_stream():full(false),buffer(0){}void Token_stream::putback(Token t){if(full)error("putback() into a full buffer");
buffer = t;
full =true;}
Token Token_stream::get(){if(full){
full =false;return buffer;}char ch;
cin >> ch;switch(ch){case';'://printcase'q':case'(':case')':case'+':case'-':case'*':case'/':case'%':returnToken(ch);case'.':case'0':case'1':case'2':case'3':case'4':case'5':case'6':case'7':case'8':case'9':{
cin.putback(ch);double val;
cin >> val;returnToken('8', val);}default:error("bad token");}}
Token_stream ts;doubleprimary(){
Token t = ts.get();switch(t.kind){case'(':{double d =expression();
t = ts.get();if(t.kind !=')')error(")expected");return d;}case'8':return t.value;case'-':return-primary();case'+':returnprimary();default:error("primary expected");}}doubleterm(){double left =primary();
Token t = ts.get();while(true){switch(t.kind){case'*':
left *=primary();
t = ts.get();break;case'/':{double d =primary();if(d ==0)error("divide by zero");
left /= d;
t = ts.get();break;}case'%':{double d =primary();int i1 =int(left);if(i1 != left)error("left-hand operand of % not int");int i2 =int(d);if(i2!=d)error("right-hand operand of % not int");if(i2 ==0)error("%divide by zero");
left = i1 % i2;
t = ts.get();break;}default:
ts.putback(t);return left;}}}doubleexpression(){double left =term();
Token t = ts.get();while(true){switch(t.kind){case'+':
left +=term();
t = ts.get();break;case'-':
left -=term();
t = ts.get();break;default:
ts.putback(t);return left;}}}intmain(){try{while(cin){
cout <<">";
Token t = ts.get();while(t.kind ==';')t = ts.get();//eat ;if(t.kind =='q'){keep_window_open();return0;}
ts.putback(t);
cout <<"="<<expression()<< endl;}keep_window_open();return0;}catch(runtime_error& e){
cerr << e.what()<< endl;keep_window_open("hpb");return1;}catch(...){
cerr <<"exception\n";keep_window_open();return2;}}
// std_lib_facilities.h/*simple "Programming: Principles and Practice using C++ (second edition)" course header tobe used for the first few weeks.It provides the most common standard headers (in t...