顺序容器的适配器
- 以顺序容器为基础构建一些常用数据结构,是对顺序容器的封装
- 栈(stack):最先压入的元素最后被弹出
- 队列(queue):最先压入的元素最先被弹出
- 优先级队列(priority_queue):最“大”的元素最先被弹出
1.利用栈反向输出单词
#include <iostream>
#include <iterator>
#include <stack>
#include <string>
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;
}
运行结果:
2.优先级队列
细胞分裂模拟
一种细胞在诞生(即上次分裂)后会在500到2000秒内分裂为两个细胞,每个细胞又按照同样的规律继续分裂。
#include <iostream>
#include <iterator>
#include <string>
#include <queue>
#include <ctime>
#include <cstdlib>
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++) { //birth为细胞诞生时间
//初始化,确定细胞分裂时间
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; //静态数据成员在main外部初始化
int main()
{
srand(static_cast<unsigned>(time(0)));
int t; //模拟时间长度
cout << "Simulation time: ";
cin >> t;
cellQueue.push(Cell(0)); //将第一个细胞压入优先级队列
while (cellQueue.top().getSplitTime() <= t) {
cellQueue.top().split(); //模拟下一个细胞的分裂
cellQueue.pop(); //将刚刚分裂的细胞弹出
}
return 0;
}
运行结果:
来自清华大学MOOC课件