集合 set
STL 在头文件 <set>
中提供了一个有序集合 set
,其中的元素全部是唯一的,并且插入进的元素自动按照升序排列,但 set
不支持通过下标定位某个元素,只能通过迭代器遍历。
以下代码声明了一个 int
类型的集合。
std::set<int> s;
使用 insert()
在集合中加入一个元素,其时间复杂度为O(logn)。
使用 erase()
删除集合中某个元素或某个位置的元素,其时间复杂度均为O(logn)。
set
自身提供 lower_bound()
用于定位元素,其作用与前文中的同名函数类似,也可以使用find()
来精确查找元素。
遍历 set
只能使用迭代器。set
的迭代器为 set<T>::iterator
,其中 T
为元素类型。
std::set<int> s;
s.insert(23333);
s.insert(23333); // 重复插入无效
s.insert(66666);
s.insert(890);
s.insert(-1);
// s.size() = 4, s = { -1, 890, 23333, 66666 }
s.erase(66666);
// s.size() = 3, s = { -1, 890, 23333 }
std::set<int>::iterator p1 = s.lower_bound(555);
// *p1 = 890
std::set<int>::iterator p2 = s.find(555);
// p2 = s.end(),因为未找到 555
s.erase(p1);
// s.size() = 2, s = { -1, 23333 }
for (std::set<int>::iterator p = s.begin(); p != s.end(); p++) {
printf("%d\n", *p);
}
// 依次输出 -1、23333
上述代码中运用的迭代器的方法在 STL 容器中较为常见。
字符串 string
STL 在头文件 <string>
中将一些与字符串有关的操作封装在了 string
内。
使用 cin
和 cout
来输入、输出字符串。
使用 find()
查找另一个字符串在该字符串中的出现位置,返回结果从 0 开始。
使用 c_str()
获得 string
对应的 const char *
类型数据,可用于向 C 库函数传递。
std::string s = "_Lyx";
int pos = s.find("23333");
// pos = string::npos,因为没有找到 23333
pos = s.find("yx");
// pos = 3,因为出现位置为第 4 个字符
char ch = s[0];
// ch = 'L'
std::cout << s << std::endl;
puts(s.c_str());
// 输出两次
队列 queue
STL 在头文件 <queue>
中提供了先入先出(FIFO)队列 queue
。
使用 push()
向队列中加入元素。
使用 front()
获取队首元素(并不删除)。
使用 pop()
删除队首元素。
使用 empty()
判断队列是否为空。
std::queue<int> q;
bool flag = q.empty();
// flag = true,队列初始为空
q.push(23333);
q.push(66666);
while (!q.empty()) {
printf("%d\n", q.front());
q.pop();
}
// 依次输出 23333,66666
栈 stack
STL 在头文件 <stack>
提供了后入先出(LIFO)栈 stack
。
使用 push()
向栈中加入元素。
使用 top()
获取栈顶元素(并不删除)。
使用 pop()
删除栈顶元素。
使用 empty()
判断栈是否为空。
std::stack<int> s;
bool flag = s.empty();
// flag = true,栈初始为空
s.push(23333);
s.push(66666);
while (!s.empty()) {
printf("%d\n", s.top());
s.pop();
}
// 依次输出 66666,23333
优先队列 priority_queue
STL 在头文件 <queue>
中提供优先队列 priority_queue
,在任意时间都能取出队列中的最大值。
使用 push()
向优先队列中加入元素,其时间复杂度为O({\log}n)O(logn)。
使用 top()
获取优先队列中最大的元素(并不删除),其时间复杂度为O(1)O(1)。
使用 pop()
删除优先队列中最大元素,其时间复杂度为O({\log}n)O(logn)。
使用 empty()
判断优先队列是否为空。
std::priority_queue<int> q;
bool flag = q.empty();
// flag = true,优先队列初始为空
q.push(23333);
q.push(-1);
q.push(66666);
while (!q.empty()) {
printf("%d\n", q.top());
q.pop();
}
// 依次输出 66666,23333,-1
priority_queue
默认提供队列中的最大值,也可以以以下声明方式让 priority_queue
提供最小值。
std::priority_queue<T, std::vector<T>, std::greater<T> > q;
注意把三个 T
换成优先队列中元素的类型(如 int
);std::greater<T>
的右边要加一个空格,否则会被编译器误认为是 >>
右移运算符。