I l@ve RuBoard Previous Section Next Section

Exercise 4.1

Create a Stack.h and a Stack.suffix, where suffix is whatever convention your compiler or project follows. Write a main() function to exercise the full public interface, and compile and execute it. Both the program text file and main() must include Stack.h:



#include "Stack.h" 

The header file for our Stack class contains the necessary header file inclusions and the actual class declaration:



#include <string> 


#include <vector> 


using namespace std; 





class Stack { 


public: 


   bool   push( const string& ); 


   bool   pop (  string &elem ); 


   bool   peek( string &elem ); 


   bool   empty() const { return _stack.empty(); } 


   bool   full()  const { return _stack.size() == _stack.max_size(); } 


   int    size()  const { return _stack.size(); } 





private: 


   vector<string> _stack; 


}; 

The Stack program text file contains the definition of the push(), pop(), and peek() member functions. Under Visual C++, the file is named Stack.cpp. It must include the Stack class header file.



#include "Stack.h" 


bool Stack::pop( string &elem ){ 


    if ( empty() ) return false; 


    elem = _stack.back(); 


    _stack.pop_back(); 


    return true; 


} 





bool Stack::peek( string &elem ){ 


    if ( empty() ) return false; 


    elem = _stack.back(); 


    return true; 


} 





bool Stack::push( const string &elem ){ 


    if ( full() ) return false; 


    _stack.push_back( elem ); 


    return true; 


} 

Here is a small program to exercise the Stack class interface. It reads in a sequence of strings from standard input, pushing each one onto the stack until either end-of-file occurs or the stack is full:



int main() { 


    Stack st; 


    string str; 





    while ( cin >> str && ! st.full() ) 


            st.push( str ); 





    if ( st.empty() ) { 


         cout << '\n' << "Oops: no strings were read -- bailing out\n "; 


         return 0; 


    } 


    st.peek( str ); 


    if ( st.size() == 1 && str.empty() ) { 


         cout << '\n' << "Oops: no strings were read -- bailing out\n "; 


         return 0; 


     } 


    cout << '\n' << "Read in " << st.size() << " strings!\n" 


         << "The strings, in reverse order: \n"; 





    while ( st.size() ) 


       if ( st.pop( str )) 


            cout << str << ' '; 





   cout << '\n' << "There are now " << st.size() 


        << " elements in the stack!\n"; 


} 

To test the program, I typed in the last sentence of the James Joyce novel, Finnegans Wake. The following is the output generated by the program (my input is in bold):



A way a lone a last a loved a long the 


Read in 11 strings! 


The strings, in reverse order: 


the long a loved a last a lone a way A 


There are now 0 elements in the stack! 
    I l@ve RuBoard Previous Section Next Section