Advertisement
Guest User

find() and count ()

a guest
Sep 9th, 2012
12
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.10 KB | None | 0 0
  1. /************ stack.h ************/
  2. #include<vector>
  3. #include<iostream>
  4. #include<algorithm>
  5. using namespace std;
  6. class stack
  7. {
  8.     public:
  9.     bool push(const string&);
  10.     bool pop(string &elem);
  11.     bool peek(string &elem);
  12.     bool empty() const {return _stack.empty();}
  13.     bool full() const {return _stack.size()==_stack.max_size();}
  14.     int size() const {return _stack.size();}
  15.     bool find(const string &elem) const;
  16.     int count(const string &elem) const;
  17.  
  18.     private:
  19.     vector<string> _stack;
  20.  
  21. };
  22.  
  23. /********** stack.cpp **********/
  24.  
  25. #include "stack.h"
  26. bool stack::push(const string& str)
  27. {
  28.     if(full()) return false;
  29.     _stack.push_back(str);
  30.     return true;
  31. }
  32. bool stack::pop(string& elem)
  33. {
  34.     if(empty()) return false;
  35.     elem = _stack.back();
  36.     _stack.pop_back();
  37.     return true;
  38. }
  39. bool stack::peek(string& elem)
  40. {
  41.     if(empty()) return false;
  42.     elem = _stack.back();
  43.     return true;
  44. }
  45. bool stack::find (const string &elem) const
  46. {
  47.     vector<string>::const_iterator it = _stack.begin();
  48.     return (::find(it,_stack.begin(),elem))!=_stack.end();
  49. }
  50. int stack::count(const string &elem) const
  51. {
  52.  
  53.     return (::count(_stack.begin(),_stack.end(),elem));
  54. }
  55.  
  56. /*********** main.cpp *************/
  57. #include "stack.cpp"
  58. #include<fstream>
  59. int main()
  60. {
  61.     stack st;
  62.     string str;
  63.     ifstream readfile("sentence.txt");
  64.     while(readfile>>str && !st.full())
  65.     {
  66.         st.push(str);
  67.     }
  68.     if (st.empty())
  69.     {
  70.         cout<<"Oops! No strings were read\n";
  71.         return 0;
  72.     }
  73.     st.peek(str);
  74.     if (st.size()==1 && str.empty())
  75.     {
  76.         cout<<"Oops! No strings were read\n";
  77.         return 0;
  78.     }
  79.     cout<<"The number of elements read are: "<<st.size()<<endl;
  80.     cout<<"The sentence in reverse order is: "<<endl;
  81.     while(!st.empty())
  82.     {
  83.         st.pop(str);
  84.         cout<<str<<' ';
  85.     }
  86.     cout<<"\nEnter a word to search: ";
  87.     cin>>str;
  88.     if(st.find(str))
  89.         cout<<"The word was found "<<st.count(str)<<" no. of times"<<endl;
  90.     else
  91.         cout<<"The word was not found"<<endl;
  92.     return 0;
  93.  
  94. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement