文章目录
- 1.deque的认识
- 1.1介绍
- 2.图析
- 2.stack模拟实现
- 3.queue模拟实现
- 4.优先级队列模拟实现
- 4.1介绍
- 4.2例题
- 4.3模拟实现
- 5.测试函数
1.deque的认识
1.1介绍
双端队列
Deque(通常读作“deck”)是double-ended queue的不规则首字母缩写。双端队列是动态长度的序列容器,可以在两端(前端或后端)伸缩。
特定的库可能以不同的方式实现deque,通常是某种形式的动态数组。但在任何情况下,它们都允许通过随机访问迭代器直接访问各个元素,存储空间通过根据需要扩展和收缩容器来自动处理。
因此,它们提供了类似于向量的功能,但可以高效地在序列的开头和末尾插入和删除元素。但是,与向量不同的是,deque不能保证将其所有元素存储在连续的存储位置上:通过偏移指向另一个元素的指针来访问deque中的元素会导致未定义的行为。
vector和deque提供了非常相似的接口,也可以用于类似的目的,但两者的内部工作方式却完全不同:vector使用单一数组,需要偶尔重新分配空间以适应增长,而deque中的元素可能分散在不同的存储块中,容器在内部保存了必要的信息,以便以常量时间和统一的顺序接口(通过迭代器)直接访问其中的任何元素。因此,deque的内部结构比vector稍微复杂一些,但这使得它们在某些情况下可以更高效地增长,特别是在序列很长时,重分配的开销会变得更大。
对于频繁地在非起始或结束位置插入或删除元素的操作,deque的性能更差,迭代器和引用的一致性也不如列表和前向列表。
Double ended queue
deque (usually pronounced like "deck") is an irregular acronym of double-ended queue. Double-ended queues are sequence containers with dynamic sizes that can be expanded or contracted on both ends (either its front or its back).
Specific libraries may implement deques in different ways, generally as some form of dynamic array. But in any case, they allow for the individual elements to be accessed directly through random access iterators, with storage handled automatically by expanding and contracting the container as needed.
Therefore, they provide a functionality similar to vectors, but with efficient insertion and deletion of elements also at the beginning of the sequence, and not only at its end. But, unlike vectors, deques are not guaranteed to store all its elements in contiguous storage locations: accessing elements in a deque by offsetting a pointer to another element causes undefined behavior.
Both vectors and deques provide a very similar interface and can be used for similar purposes, but internally both work in quite different ways: While vectors use a single array that needs to be occasionally reallocated for growth, the elements of a deque can be scattered in different chunks of storage, with the container keeping the necessary information internally to provide direct access to any of its elements in constant time and with a uniform sequential interface (through iterators). Therefore, deques are a little more complex internally than vectors, but this allows them to grow more efficiently under certain circumstances, especially with very long sequences, where reallocations become more expensive.
For operations that involve frequent insertion or removals of elements at positions other than the beginning or the end, deques perform worse and have less consistent iterators and references than lists and forward lists.
2.图析
2.stack模拟实现
#pragma once
#include <iostream>
#include <assert.h>
#include <deque>
using namespace std;
namespace apex
{ // Double-ended queue 双端队列
template<class T, class Container = deque<T>>
class stack
{
public:
//压栈 -- 栈顶入数据 -- 尾插
void push(const T& x)
{
_con.push_back(x);
}
//出栈 -- 栈顶出数据 -- 尾插
void pop()
{
_con.pop_back();
}
//取栈顶 -- 数据的尾部 -- back()函数
T& top()
{
return _con.back();
}
const T& top() const
{
return _con.back();
}
//判空 -- 对象的empty函数
bool empty() const
{
return _con.empty();
}
//栈大小 -- size函数
size_t size() const
{
return _con.size();
}
private:
Container _con;
};
}
3.queue模拟实现
#pragma once
#include <deque>
namespace apex
{
template<class T, class Container = deque<T>>
class queue
{
public:
//入队列 -- 尾插
void push(const T& x)
{
_con.push_back(x);
}
//出队列 -- 头删
void pop()
{
_con.pop_front();
}
//取队尾 -- back函数
T& back()
{
return _con.back();
}
const T& back() const
{
return _con.back();
}
//取队头 -- front函数
T& front()
{
return _con.front();
}
const T& front() const
{
return _con.front();
}
//判空 -- empty函数
bool empty() const
{
return _con.empty();
}
//队列大小 -- size函数
size_t size() const
{
return _con.size();
}
private:
Container _con;
};
}
4.优先级队列模拟实现
4.1介绍
优先队列
优先级队列是一种容器适配器,根据某种严格的弱排序标准,特别设计为它的第一个元素总是它所包含的元素中的最大元素。
这个上下文类似于堆(heap),在堆中可以随时插入元素,但只能取得堆中最大的元素(优先队列中最上面的那个)。
优先队列是作为容器适配器实现的,容器适配器是使用特定容器类的封装对象作为其底层容器的类,提供一组特定的成员函数来访问其元素。元素从特定容器的“后面”弹出,也就是优先队列的顶部。
底层容器可以是任何标准容器类模板,也可以是其他专门设计的容器类。该容器应可通过随机访问迭代器访问
标准容器类vector和deque可以满足这些需求。默认情况下,如果没有为特定的priority_queue类实例化指定容器类,则使用标准容器向量。
支持随机访问迭代器需要始终在内部保持堆结构。这是由容器适配器自动完成的,在需要时自动调用算法函数make_heap、push_heap和pop_heap。
Priority queue
Priority queues are a type of container adaptors, specifically designed such that its first element is always the greatest of the elements it contains, according to some strict weak ordering criterion.
This context is similar to a heap, where elements can be inserted at any moment, and only the max heap element can be retrieved (the one at the top in the priority queue).
Priority queues are implemented as container adaptors, which are classes that use an encapsulated object of a specific container class as its underlying container, providing a specific set of member functions to access its elements. Elements are popped from the "back" of the specific container, which is known as the top of the priority queue.
The underlying container may be any of the standard container class templates or some other specifically designed container class. The container shall be accessible through random access iterators and support the following operations:
empty()
size()
front()
push_back()
pop_back()
The standard container classes vector and deque fulfill these requirements. By default, if no container class is specified for a particular priority_queue class instantiation, the standard container vector is used.
Support of random access iterators is required to keep a heap structure internally at all times. This is done automatically by the container adaptor by automatically calling the algorithm functions make_heap, push_heap and pop_heap when needed.
4.2例题
class solution
{
public:
int findKthLargest(vector<int>& nums, int k)
{
//创建堆 -- O(N)
priority_queue<int> maxHeap(nums.begin(), nums.end());
//pop k-1 个数据 -- O(k * logN)
while (--k)
maxHeap.pop();
return maxHeap.top();
}
};
4.3模拟实现
5.测试函数
#include <iostream>
#include <stack>
#include <queue>
#include <vector>
#include <list>
#include <algorithm>
#include <functional>
#include <time.h>
using namespace std;
#include "Stack.h"
#include "Queue.h"
#include "PriorityQueue.h"
//栈的测试
void test_stack()
{
stack<int> st;
//stack<int, vector<int>> st;
//stack<int, list<int>> st;
st.push(1);
st.push(2);
st.push(3);
st.push(4);
while (!st.empty())
{
cout << st.top() << endl;
st.pop();
}
}
//队列的测试
void test_queue()
{
queue<int> q;
//queue<int, list<int>> q;
//queue<int, vector<int>> q;
q.push(1);
q.push(2);
q.push(3);
q.push(4);
while (!q.empty())
{
cout << q.front() << endl;
q.pop();
}
}
void test_priority_queue()
{
// 默认大的优先级高
priority_queue<int> pq;
pq.push(1);
pq.push(2);
pq.push(3);
pq.push(4);
pq.push(5);
pq.push(0);
while (!pq.empty())
{
cout << pq.top() << " ";
pq.pop();
}
cout << endl;
//5 4 3 2 1 0
int a[] = { 1,2,3,4,5,0 };
priority_queue<int> i_pq1(a, a + sizeof(a) / sizeof(int));//迭代器区间构造
//优先级队列原型
//template <class T, class Container = vector<T>, class Compare = less<typename Container::value_type> >
priority_queue<int, vector<int>, greater<int>> i_pq2(a, a + sizeof(a) / sizeof(int));
while (!i_pq2.empty())
{
cout << i_pq2.top() << " ";
i_pq2.pop();
}
cout << endl;
//0 1 2 3 4 5
}
//vector比deque快大约2倍
void test_op()
{
srand(time(0));
const int N = 100000;
vector<int> v;
v.reserve(N);
deque<int> dp;
for (int i = 0; i < N; ++i)
{
auto e = rand();
v.push_back(e);
dp.push_back(e);
}
int begin1 = clock();
sort(v.begin(), v.end());
int end1 = clock();
int begin2 = clock();
sort(dp.begin(), dp.end());
int end2 = clock();
printf("vector sort:%d\n", end1 - begin1);
printf("deque sort:%d\n", end2 - begin2);
}
int main()
{
test_priority_queue();
return 0;
}