Exercise 4.2

Extend 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. ...

Get Essential C++ now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.