stack和queue
用栈实现队列
class MyQueue {
public:
MyQueue() {
}
void inout()
{
while(!stinput.empty())
{
int top=stinput.top();
stinput.pop();
stoutput.push(top);
}
}
void push(int x) {
stinput.push(x);
}
int pop() {
if(stoutput.empty())
{
inout();
}
int x=stoutput.top();
stoutput.pop();
return x;
}
int peek() {
if(stoutput.empty())
{
inout();
}
return stoutput.top();
}
bool empty() {
return stinput.empty()&&stoutput.empty();
}
private:
stack<int> stinput;
stack<int> stoutput;
};
用队列实现栈
class MyStack {
public:
MyStack() {
}
void push(int x) {
q2.push(x);
while(!q1.empty())
{
q2.push(q1.front());
q1.pop();
}
swap(q1,q2);
}
int pop() {
int r=q1.front();
q1.pop();
return r;
}
int top() {
int r=q1.front();
return r;
}
bool empty() {
return q1.empty();
}
private:
queue<int> q1;
queue<int> q2;
};
栈排序
栈排序。 编写程序,对栈进行排序使最小元素位于栈顶。最多只能使用一个其他的临时栈存放数据,但不得将元素复制到别的数据结构(如数组)中。该栈支持如下操作:push、pop、peek 和 isEmpty。当栈为空时,peek 返回 -1
class SortedStack {
stack<int> ast;
stack<int> dst;
public:
SortedStack() {
}
void push(int val) {
while(!ast.empty()&&ast.top()>val)
{
dst.push(ast.top());
ast.pop();
}
while(!dst.empty()&&dst.top()<val)
{
ast.push(dst.top());
dst.pop();
}
dst.push(val);
}
void pop() {
while(!ast.empty())
{
dst.push(ast.top());
ast.pop();
}
if(!dst.empty())
dst.pop();
}
int peek() {
while(!ast.empty())
{
dst.push(ast.top());
ast.pop();
}
if(!dst.empty())
return dst.top();
else
return -1;
}
bool isEmpty() {
return ast.empty()&&dst.empty();
}
};
维护一个升序栈(辅助队列)和降序栈
priority_queue
知识点
1.默认用vector,默认是大堆(大的优先级高)仿函数less。
2. 需要支持随机访问迭代器,以便始终在内部保持堆结构。容器适配器通过在需要时自动调用算法函数make_heap、push_heap和pop_heap来自动完成此操作。
3.如果要用小堆,如下
void test_std_pq()
{
priority_queue<int, vector<int>, greater<int>> pq;//小堆
pq.push(1);
pq.push(0);
pq.push(5);
pq.push(2);
pq.push(1);
pq.push(7);
while (!pq.empty())
{
cout << pq.top() << " ";
pq.pop();
}
cout << endl;
}
这里用到了仿函数
仿函数
仿函数(Functor)又称为函数对象(Function Object)是一个能行使函数功能的类。仿函数的语法几乎和我们普通的函数调用一样,不过作为仿函数的类,都必须重载operator()运算符。因为调用仿函数,实际上就是通过类对象调用重载后的operator()运算符。
小式牛刀
实现一个小于的仿函数
template<class T>
struct Less
{
bool operator()(const T& x, const T& y)
{
return x < y;
}
};
仿函数成员变量作用
class StringAppend
{
public:
explicit StringAppend(const string& str) : ss(str) {}
void operator() (const string& str) const
{
cout << str << ' ' << ss << endl;
}
private:
const string ss;
};
int main()
{
StringAppend myFunctor2("and world!");
myFunctor2("Hello");
return 0;
}
输出hello and world
它既能像普通函数一样传入给定数量的参数,还能存储或者处理更多我们需要的有用信息