承接上一篇,我们继续来感受STL的奇妙:
//栈的实现
# include <iostream>
# include <string>
# include <iterator>
# include <stack>
using namespace std;
int main()
{
stack<char>s;
string str;
cin>>str;
for(string::iterator iter = str.begin(); iter != str.end(); ++iter)
{
s.push(*iter);
}
while(!s.empty())
{
cout<<s.top();
s.pop();
}
cout<<endl;
return 0;
}
# endif
# if 1
//容器适配器之优先级队列,,每次弹出的是最大的元素,与压入顺序无关
//优先级队列(模拟细胞分裂)
# include<iostream>
# include <queue>
# include <cstdlib>
# include <ctime>
using namespace std;
const int SPLIT_TIME_MIN = 500;//细胞分裂最短时间
const int SPLIT_TIME_MAX = 2000;//细胞分裂最长时间
class cell;
priority_queue<cell>cellQueue;//优先级队列
class cell
{
private:
static int count;//细胞数目
int id;//细胞编号
int time;//分裂时间
public:
cell(int birth):id(count++)
{
time = birth + (rand()%(SPLIT_TIME_MAX - SPLIT_TIME_MIN))+SPLIT_TIME_MIN;
}
int GetId() const
{
return id;
}
int GetSplitTime() const
{
return time;
}
bool operator < (const cell &s) const
{
return time > s.time;
}
void split()
{
cell child1(time),child2(time);//建立两个子细胞
cout<<time<<"s: cell#"<<id<<"splits to #"<<child1.GetId ()<<"and #"<<child2.GetId ()<<endl;
cellQueue.push(child1);
cellQueue.push(child2);
}
};
int cell::count = 0;
int main()
{
srand(static_cast <unsigned>(time(0)));
int t;
cout<<"simmulation time:";
cin>>t;
cellQueue.push(cell(0));
while(cellQueue.top().GetSplitTime () <= t)
{
cellQueue.top().split ();
cellQueue.pop();
}
return 0;
}
# endif
//STL之关联容器set、map
//分类:单重关联(键值唯一)多重关联(键值不唯一)
# if 1
//集合set
//找重复元素
# include<set>
# include <iterator>
# include <utility>//pair结构体模板的头文件
# include<iostream>
using namespace std;
int main()
{
set<double>s;
while(1)
{
double v;
cin>>v;
if(v == 0) break;
pair<set<double>::iterator , bool> r = s.insert(v);
if(!r.second)
{
cout<<v<<"已存在!"<<endl;
}
}
set<double>::iterator iter1 = s.begin();
set<double>::iterator iter2 = s.end();
double medium = (*iter1 + *(--iter2))/2;
cout<<"<= medium:";
copy(s.begin(), s.upper_bound(medium), ostream_iterator<double>(cout, " "));
cout<<endl;
cout<<">= medium:";
copy(s.upper_bound(medium),s.end(), ostream_iterator<double>(cout, " "));
cout<<endl;
return 0;
}
# endif
# if 1
//求输入字符串中各个字母的个数
//映射map
# include<iostream>
# include <map>
# include <cctype>
using namespace std;
int main()
{
map<char, int>s;
char c;
do
{
cin>>c;
if(isalpha(c))//判断是否是字母
{
c = tolower(c);//转化为小写
s[c]++;//次数加一
}
}while(c!='*');//*表示结束输入
for(map<char, int>::iterator iter = s.begin(); iter!=s.end(); iter++)
{
cout<<iter->first<<":"<<iter->second<<" ";
cout<<endl;
}
cout<<endl;
return 0;
}
# endif