1.20的STL学习
一.string
1.strlen()的复杂度为o(n),而.length()的复杂度为o(1);
2.find()函数的用法:
string s1("11123456");
int p = -1;
//寻找所有的"1"的位置
while (s1.find("1", p + 1) != -1) {//如果找不到find()行数返回-1
p = s1.find("1", p + 1);
cout << p << "\n";
}
二.erase的使用误区
set<int>didt;//错误示范
for (int i = 1; i <= 10; i++) {
didt.insert(i);
}
set<int>::iterator it;
for (it = didt.begin(); it != didt.end(); it++) {
if (*it == 8) {
didt.erase(*it);
}
printf("%d ", *it);
}
原因:当didt.erase(iter)之后,it就变成了一个野指针,对一个野指针进行 it++ 是肯定会出错的。
对于erase的返回值是这样描述的:An iterator that designates the first element remaining beyond any elements removed, or a pointer to the end of the vector if no such element exists
for (it = didt.begin(); it != didt.end(); it++) {
if (*it == 8) {
it=didt.erase(it);
}
printf("%d ", *it);
}
这样也有两个错误:
1.无法删除连续的8;
2.无法删除结尾的数
正解
for (it = didt.begin(); it != didt.end();) {
if (*it == 8) {
it=didt.erase(it);
}
else{
it++;
}
printf("%d ", *it);
}
三.题目
1.hdu-1263(map的嵌套)
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
#include<cmath>
#include<string>
#include<map>
using namespace std;
int main() {
int t;
map<string, map<string, int>>mp;
scanf("%d", &t);
while (t--) {
int n;
mp.clear();
cin >> n;
for (int i = 1; i <= n; i++) {
string s1, s2;
int a;
cin >> s1 >> s2 >> a;
if (mp.count(s2) == 0) {//count(x)返回x出现的次数
mp[s2] = map<string, int>();
}
mp[s2][s1] += a;
}
for (auto x : mp) {
cout << (x.first) << "\n";
for (auto y : x.second) {
cout << " |----" << y.first << "(" << y.second << ")" << "\n";
}
}
if (t)cout << "\n";
}
return 0;
}
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
#include<cmath>
#include<string>
#include<queue>
using namespace std;
const int MAXN = 1e5 + 10;
int n;
struct Node {
int k;
int id;
Node(int k1, int id1) {
k = k1;
id = id1;
}
bool friend operator<(const Node& n1, const Node& n2) {//大根堆大或小于号要取反
if (n1.k != n2.k)return n1.k < n2.k;
return n1.id > n2.id;
}
};
priority_queue<Node>qu[4];
int main() {
while (~scanf("%d", &n)) {
for (int i = 1; i <= 3; i++) {//清空
while (!qu[i].empty())qu[i].pop();
}
int id = 0;
for (int i = 1; i <= n; i++) {
string s;
cin >> s;
if (s == "IN") {
int x, y;
++id;
cin >> x >> y;
qu[x].push(Node(y, id));
}
else {
int x;
cin >> x;
if (qu[x].empty())puts("EMPTY");
else {
cout << qu[x].top().id << "\n";
qu[x].pop();
}
}
}
}
return 0;
}