stack操作

Stack.h

#ifndef STACK_H_
#define STACK_H_

class Stack
{
public:

bool find(const string &elem) const;//查找某值
int count(const string &elem) const;//计算次数
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;
};
#endif


Stack.cpp

#include<string>
#include<vector>
#include "Stack.h"
using namespace std;


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;
}


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);
}


main.cpp

#include<iostream>
#include<string>
#include<vector>
#include "Stack.h"
using namespace std;


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";


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


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";
}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值