1、栈(stack)
底层用deque(缺省是deque,封闭其头端开口)或者list(如stack<int, list> isstack)实现均可,这俩都是双向开口的数据结构。
- bool empty() 判断是否为空
- size_type size() 大小
- void push(const value_type& x) 入栈
- void pop() 出栈,这里调用底层序列容器的pop_back,和队列有区别
- reference top()获取栈顶
stack不提供走访功能,也不提供迭代器
2、队列(queue)
底层用deque(缺省是deque,封闭头部入、尾部出口)或者list(如queue<int, list> isstack)实现均可,这俩都是双向开口的数据结构。
- bool empty() 判断是否为空
- size_type size() 大小
- void push(const value_type& x) 入列
- void pop() 出列,这里调用底层序列容器的pop_front,和栈有区别
- reference front()获取队列头部的元素,底层调用c.front
- reference back()获取队列尾部的元素,底层调用c.back
queue不提供走访功能,也不提供迭代器
3、unordered_map哈希表
unordered_map 底层用hash实现,C++ 11引入
初始化:
unordered_map<int, int> mapping;
unordered_map<string, vector<int>> mapping;
常用成员函数:
size_type size();
bool empty();
// 返回哈希表中key出现的次数
// 因为哈希表不会出现重复的键,所以该函数值可能返回0或者1
// 可以用于判断键key是否存在于哈希表中
size_type count (const key_type & key);
size_type erase(const key_type& key);
vector<int> nums{1,1,3,4,5,3,6};
unordered_map<int, int> counter;
for (int num : nums) {
// 注意这里如果key不存在,会自动创建key,对应的值为值类型的默认值
counter[num]++;
}
for (auto &it: counter) {
int key = it.first;
int val = it.second;
cout<< key << ": " << val << endl;
}
4、堆 priority_queue
默认是大顶堆
priority_queue<int, vector, greater >f;
也可以是小顶堆
priority_queue<int, vector, less >f;
常见操作:
-
int x = f.top();
-
f.pop();
-
f.push(x);
5、deque双向队列
相比queue可能在前方插入和弹出,底层多使用了一个缓冲区
常见操作:
deque que;
- que.push_back(const value_type &val);
- que.push_front(const value_type &val);
- que.pop_back();
- que.pop_front();
- que.size();
- que.clear(); //清除所有元素
示例:剑指 Offer 32 - III. 从上到下打印二叉树 III
支持迭代器
如:
deque<int, alloc, 8>::iterator itr;
itr = find(que.begin(), que.end(), 99);
cout<< *itr <<endl;
cout<< *(itr.cur) <<endl;
6、map字典
有迭代器
7、unordered_set集合
unordered_set set;
set.insert(value);
set.erase(value);
set.find(value) == set.end();
常见函数
1、C语言中有strcmp
strcmp函数是string compare(字符串比较)的缩写,用于比较两个字符串并根据比较结果返回整数。基本形式为strcmp(str1,str2),若str1=str2,则返回零;若str1str2,则返回正数。
2、C++语言中
int 转 string : c++ 11支持to_string方法,需要引入#include ;
string to_string (int val);
string to_string (long val);
string to_string (long long val);
string to_string (unsigned val);
string to_string (unsigned long val);
string to_string (unsigned long long val);
string to_string (float val);
string to_string (double val);
string to_string (long double val);
string转int:atoi、atol等
#include <stdio.h>
string s = "12";
int a = atoi(s.c_str());