global scope[全局范围]运算符
问题描述
建立Stack.h与Stack.suffix.此处的suffix是你的编译器所能接受的扩展名,或是你的项目所使用的扩展名.(一般来说为.c,.cc,.cpp或.cxx).撰写main()函数,练习操作Stack的所有公开接口,并加以编译执行,程序代码文件和main()都必须含入Stack.h:
代码撰写(已经过测试)
Stack.h
//需要注意的是Stack class所在的头文件中必须含入必要的头文件
#include <string>
#include <vector>
using namespace std;
class Stack{
public:
bool push(const string&);
bool pop(string &elem);
bool peek(string &elem);
bool empty();
bool full();
int size(){return _stack.size();}
private:
vector<string> _stack;
};
inline bool
Stack::empty()
{
return _stack.empty();
}
inline bool Stack::full()
{ return _stack.size()==_stack.max_size();}
Stack.suffix
//在Stack class的程序代码文件中定义push(),pop(),peek()等函数
//该文件必须含入Stack.h文件
#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;
//back运算符返回最末一个元素
elem=_stack.back();
return true;
}
bool Stack::push(const string &elem)
{
if(full())
return false;
_stack.push_back(elem);
return true;
}
main.cpp
//#include "Stack.h"
#include <iostream>
#include "Stack.suffix"
int main()
{
Stack st;
string str;
while(std::cin>>str && !st.full()&& std::cin.get() != '\n')
st.push(str);
if(st.empty()){
cout<<'\n'<<"Oops: no string were read --bailing out \n";
return 0;
}
st.peek(str);
if(st.size()==1 && str.empty()){
cout<<'\n'<<"Oops: no string were read --bailing out \n";
return 0;
}
std::cout<<'\n'<<"Read in "<<st.size()<<" String !\n"
<<"The strings, in reverse order:\n";
while(st.size())
if(st.pop(str))
std::cout<<str<<' ';
return 0;
}
代码补充
延伸Stack的功能,支持find()和cout()两个功能,find检查某值是否存在而返回true或false。cout()返回某字符串的出现次数。
第一时间应该想到泛型算法
马上又要想到命名空间的问题
#include <algorithm>
bool Stack::find()(const string &elem) cosnt{
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);}
其中涉及到global scope(全局范围)运算符的问题
今天小知识
c++中cin默认情况下是不以enter为结束符的
设计类的时候,如何使用泛型算法
今天没想清楚的问题下面代码中empty()的使用,为什么不是对象.empty() 的形式
bool
Stack::pop(string &elem)
{
if(empty())
return false;
elem=_stack.back();
_stack.pop_back();
return true;
}