马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有账号?立即注册
×
一、set
1、size / empty
size:返回set中实际元素的个数
empty:判定set是否为空
2、begin / end
这是两个迭代器,因此可以使用范围for来遍历整个红黑树。其中,遍历是按照中序遍历的顺序,因此是一个有序序列。
3、insert / erase
insert:向红黑树中插入一个元素
erase:删除一个元素
4、find / count
find:查找一个元素,返回的是迭代器
count:查询元素出现的次数
假如想查找元素是否在set中,我们一样寻常不使用find,而是使用count。因为find的返回值是一个迭代器,判定起来不方便。
5、lower_bound / upper_bound
lower_bound:大于等于x的最小元素,返回的是迭代器
upper_bound:大于x的最小元素,返回的是迭代器
6、全部测试代码
- #include <iostream>
- #include <set>
- using namespace std;
- int a[] = { 10,60,20,70,80,30,90,40,100,50 };
- int main()
- {
- set<int> mp;
- for (auto e : a)
- {
- mp.insert(e);
- }
- for (auto x : mp)
- {
- cout << x << " ";
- }
- cout << endl;
- if (mp.count(1))
- cout << "1" << endl;
- if (mp.count(10))
- cout << "10" << endl;
- mp.erase(10);
- if (mp.count(10))
- cout << "YES" << endl;
- else
- cout << "NO" << endl;
- auto x = mp.lower_bound(20);
- auto y = mp.upper_bound(20);
- cout << *x << " " << *y << endl;
- return 0;
- }
复制代码 二、map
map与set的区别:set内里存储的是一个单独的关键字(也就是存一个int、char、double或者string)。而map内里存的是一个pair<key, value>(k-v模型),不仅有一个关键字,还有一个与关键字绑定的值,比较方式是按照key的值来比较。好比,我们可以在map中存<string, int>来统计字符串出现的次数。
1、insert
向红黑树中插入一个元素。这里必要一个pair,可以用{}的情势。
- #include <iostream>
- #include <map>
- using namespace std;
- void print(map<string, int>& mp)
- {
- for (auto& p : mp)
- {
- cout << p.first << " " << p.second << endl;
- }
- }
- int main()
- {
- map<string, int> mp;
- mp.insert({ "zhangsan", 1 });
- mp.insert({ "lisi", 2 });
- mp.insert({ "wangwu", 3 });
- print(mp);
- return 0;
- }
复制代码 2、operator[]
重载[],使得map可以像数组一样使用。
- #include <iostream>
- #include <map>
- using namespace std;
- void print(map<string, int>& mp)
- {
- for (auto& p : mp)
- {
- cout << p.first << " " << p.second << endl;
- }
- }
- int main()
- {
- map<string, int> mp;
- mp.insert({ "zhangsan", 1 });
- mp.insert({ "lisi", 2 });
- mp.insert({ "wangwu", 3 });
- print(mp);
- cout << mp["zhangsan"] << endl;
- mp["zhangsan"] = 110;
- cout << mp["zhangsan"] << endl;
- return 0;
- }
复制代码 三、例题
算法原理:求出最小波动值,我们只必要针对某一天的业务额,找出前面的数中哪个数离它最近(大于等于x的最小值 或者 小于等于x的最大值)。前一种环境可以调用lower_bound函数,后一种环境可以使用迭代器来解决。
- #include <iostream>
- #include <set>
- using namespace std;
- const int INF = 1e7 + 10;
- int n;
- set<int> mp;
- int main()
- {
- cin >> n;
- int ret;
- cin >> ret;
- mp.insert(ret);
- mp.insert(-INF);
- mp.insert(INF);
- for (int i = 2;i <= n;i++)
- {
- int x;
- cin >> x;
- auto it = mp.lower_bound(x);
- auto tmp = it;
- tmp--;
- if (*it == x)
- continue;
- ret += min(abs(*tmp - x), abs(*it - x));
- mp.insert(x);
- }
- cout << ret << endl;
- return 0;
- }
复制代码
|