set - 有序集合 | 红黑树
C++之STL整理(4)之set 用法(创建、赋值、增删查改)详解
基本使用
输入
3 1 2 9 1 5 1 6 5 4
代码
#include <bits/stdc++.h>
using namespace std;
int main() {
set<int> asc; // 默认递增排序
set<int, greater<int>> desc;
set<int>::iterator itlow, itup;
for(int i = 0; i < 10; i++) {
int a;
cin >> a;
asc.insert(a);
desc.insert(a);
}
for (auto& i : asc) cout << i << " ";
cout << endl;
for (auto& i : desc) cout << i << " ";
cout << endl;
// 使用lower_bound、upper_bound的前提是序列是有序的!!!
itlow = asc.lower_bound(3);
itup = asc.upper_bound(6);
cout << "The lower bound of 3 in asc (大于等于3的最小数): " << *itlow << endl;
cout << "The upper bound of 6 in asc (大于6的最小数): " << *itup << endl;
vector<int> aa = {2, 5, 6, 8, 9, 12};
vector<int>::iterator vitlow, vitup;
vitlow = lower_bound(aa.begin(), aa.end(), 6);
vitup = upper_bound(aa.begin(), aa.end(), 8);
// vector支持随机访问,可以用“vitlow - aa.begin()”获取元素下标;
// 但是set不支持随机存取,所以不能通过iterator获取元素下标
cout << "The index of 6 in aa: " << vitlow - aa.begin() << endl;
cout << "The upper bound of 8 in aa: " << *vitup << endl;
return 0;
}
输出
1 2 3 4 5 6 9
9 6 5 4 3 2 1
The lower bound of 3 in asc (大于等于3的最小数): 3
The upper bound of 6 in asc (大于6的最小数): 9
The index of 6 in aa: 2
The upper bound of 8 in aa: 9
find - 查找元素
代码
// find example
#include <iostream> // std::cout
#include <algorithm> // std::find
#include <vector> // std::vector
int main () {
// using std::find with array and pointer:
int myints[] = { 10, 20, 30, 40 };
int * p;
p = std::find (myints, myints+4, 30);
if (p != myints+4)
std::cout << "Element found in myints: " << *p << '\n';
else
std::cout << "Element not found in myints\n";
// using std::find with vector and iterator:
std::vector<int> myvector (myints,myints+4);
std::vector<int>::iterator it;
it = find (myvector.begin(), myvector.end(), 30);
if (it != myvector.end())
std::cout << "Element found in myvector: " << *it << '\n';
else
std::cout << "Element not found in myvector\n";
return 0;
}