目录
STL
容器
list
特性
STL所提供list容器是双向链表,它的“插入和删除操作”的复杂度是常数的
list的优缺点与vector正好相反
list的插入和删除频繁,随机访问少
vector随机访问频繁,插入和删除少
例题
来一道例题感受一下用法ovo
题目链接
代码
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
int k = 2;
list<int> li;
list<int>::iterator it;
for (int i = 1; i <= n; i++)li.push_back(i);
while (li.size() > 3) {
int cnt = 1;
for (it = li.begin(); it != li.end();) {
if (cnt++ % k == 0) it = li.erase(it);
else it++;
}
k == 2 ? k++ : k = 2;
}
it = li.begin();
cout << *it++;
for (; it != li.end(); it++) {
cout << ' ' << *it;
}
cout << '\n';
}
return 0;
}
函数
sort()自带的排序规则
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
vector<int>a={3,4,8,2,9,1,7,5,6};
sort(a.begin(),a.begin()+4);//对前四个从小到大排序
sort(a.begin(),a.end());//全部从小到大排序
sort(a.begin(),a.end(),less<int>());//按int从小到大排序
sort(a.begin(), a.end(), greater<int>());//按int从大到小排序
return 0;
}
stable_sort()稳定排序
在遇到相同元素时,保留原来顺序
举例说明
案例生成代码
#include <bits/stdc++.h>
#include <utility>
using namespace std;
const int num = 20;
struct node {//申明结构体进行排序
int n;
string s;
node() {}
node(int n, string s) : n(n), s(std::move(s)) {}
} np[num], np2[num], npn[num];//npn是原本未排序的
//自定义排序函数
bool cmp(node a, node b) {
return a.n < b.n;
}
int main() {
ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
srand((int) time(0));
string s = "123456";
//制造结构体数组
for (int i = 0; i < num; i++) {
npn[i] = np[i] = np2[i] = {rand() % 2, s};
next_permutation(s.begin(), s.end());//这个函数下面有讲
}
sort(np, np + num, cmp);
stable_sort(np2, np2 + num, cmp);
cout << "initial | sort | stable_sort\n";
for (int i = 0; i < num; i++) {
cout << npn[i].n << ' ' << npn[i].s << " | " << np[i].n << ' ' << np[i].s << " | " << np2[i].n << ' '
<< np2[i].s <<
endl;
}
return 0;
}
输出结果
可以看到,根据结构体的第一个元素排序,对于两种排序,结构体的第二个元素顺序不一样
与初始数组对比可以发现,stable_sort()在遇到n相同的元素时,会保留原本的顺序。
不过stable_sort()的排序速度要更慢。
partial_sort()部分排序
可以得出数组中最小的几个元素
partial_sort(begin, middle, end)
根据middle
比如下面的代码
#include <bits/stdc++.h>
#include <utility>
using namespace std;
int main() {
ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
srand((int) time(0));
int a[20];
for (auto &i : a)i = rand() % 100;
//排序前
for (auto i:a)cout << i << ' ';
cout << endl;
partial_sort(a, a + 6, a + 20);//将最小的六个元素排序并放在数组的最前面,其余元素仍然乱序
//排序后
for (auto i:a)cout << i << ' ';
cout << endl;
return 0;
}
值得注意的是,如果middle与end相等,它的效果与sort()一样
next_permutation()全排列
这个函数能够得出一个数组或容器的全排列结果
返回值为布尔值,如果没有下一个排列组合,则返回false,否则返回true
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
string s = "123";
do {
cout << s << endl;
} while (next_permutation(s.begin(), s.end()));
return 0;
}
得到结果
对于数组或其他容器来说,传递的值大体相同。
输入输出
cin与cout
众所周知,cin与cout都很慢
但是它很方便
有一种方法可以加速cin与cout,加速后基本满足大部分题目的输入输出要求
只要在main里面加一行
ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);