I l@ve RuBoard |
![]() ![]() |
Exercise 4.2Extend the Stack class to support both a find() and a count() operation. find() returns true or false depending on whether the value is found. count() returns the number of occurrences of the string. Reimplement the main() of Exercise 4.1 to invoke both functions. We implement these two functions simply by using the corresponding generic algorithms of the same names: #include <algorithm> bool Stack::find( const string &elem ) const { vector<string>::const_iterator end_it = _stack.end(); return ::find( _stack.begin(), end_it, elem ) != end_it; } int Stack::count( const string &elem ) const { return ::count( _stack.begin(), _stack.end(), elem ); } The global scope operator is necessary for the invocation of the two generic algorithms. Without the global scope operator, for example, the unqualified invocation of find() within find() recursively invokes the member instance of find()! The Stack class declaration is extended to include the declarations of these two functions: class Stack { public: bool find( const string &elem ) const; int count( const string &elem ) const; // ... everything else the same ... }; The program now inquires of the user which word she would like to search for and reports whether it is within the stack and, if so, how many times it occurs: int main() { Stack st; string str; while ( cin >> str && ! st.full() ) st.push( str ); // check for empty stack as before ... cout << '\n' << "Read in " << st.size() << " strings!\n"; cin.clear(); // clear end-of-file set ... cout << "what word to search for? "; cin >> str; bool found = st.find( str ); int count = found ? st.count( str ) : 0; cout << str << (found ? " is " : " isn\'t " ) << "in the stack. "; if ( found ) cout << "It occurs " << count << " times\n"; } Here is an interactive execution of the program. The items highlighted in bold are what I entered: A way a lone a last a loved a long the Read in 11 strings! what word to search for? a a is in the stack. It occurs 4 times ![]() |
I l@ve RuBoard |
![]() ![]() |