set基于红黑树实现所以有序
unorder_set基于哈希表实现所以顺序不定
#include <vector>
#include <string>
#include <iostream>
#include <list>
#include <iterator>
#include <deque>
#include <stack>
#include <queue>
#include <algorithm>
#include <set>
#include <unordered_set>
using namespace std;
// set 与 multiset 底层机制为 RB_tree (有序)
// unordered_set unordered_multiset 底层机制为 hash table (无序)
int main()
{
set<int> s1 = {6,2,7,3,9};
set<int> s2{6,2,7,3,9,3};
vector<int> v1 = {2,4,6,3,5,9};
//set<int> s3(v1); //error
set<int> s4(v1.begin(),v1.end()); //v1顺序不变
for(auto tmp:s2)
cout << tmp << ","; //2,3,6,7,9, 自动排序,自动去重
cout << endl;
set<int>::iterator it1 = s1.find(2); //返回迭代器 没找到返回的是 s1.end();
//*it1 = 888; // 不可以用迭代器改变 set内部的值
s1.erase(2);
s1.insert(3); // 有3,就什么都不做
cout << s1.count(3) << endl; // 1 有则为1,无则为0
s1.clear();
s1.swap(s2);
s1.size();
s1.empty();
s1.max_size();
//查找
s1 = {0,1,2,3,4,5,6,7,8};
pair<set<int>::iterator, set<int>::iterator> pair1 = s1.equal_range(5); //返回全是5的【)区间
cout << *pair1.first << endl; //5
cout << *pair1.second << endl; //6
//查找
set<int>::iterator it2 = s1.lower_bound(5); //二分查找 第一个 <=5的迭代器 找不到 返回迭代器 end();
cout << "lower_bounder:<=5所在的迭代器位置" << *it2 << endl; //5
set<int>::iterator it3 = s1.upper_bound(5); //二分查找 第一个 >5的迭代器 找不到 返回 end();
cout << "lower_bounder:>5所在的迭代器位置" << *it3 << endl; //6
s1 = {22,44,99};
set<int>::iterator it4 = s1.begin();
cout << "从后向前:" << *(--it4) << endl; //3
it4 = s1.end();
cout << "最后一位:" << *it4 << endl; //3
//set的iterator是 一个循环 "begin()--" 内容是 set内元素个数 begin()--就是 end();
// s1.key_comp();
// s1.value_comp();
// s1.emplace_hint();
// s1.get_allocator();
// s1.~set();
// s1._M_t;
multiset<int> multiset1 = {1,2,3,3,5,9,4}; //自动排序 不去重
for(auto tmp:multiset1)
cout << tmp << ","; //1,2,3,3,4,5,9
cout << endl;
unordered_set<int> u_set1 = {1,2,3,3,5,9,4}; //无序 去重
for(auto tmp:u_set1)
cout << tmp << ","; //4,9,5,3,2,1,
cout << endl;
// 元素被存放在哈希表内部的格子中。每个格子保存哪个元素,是由元素的哈希值决定的。
unordered_multiset<int> u_mset1{1,2,3,3,5,9,4}; //无序 不去重
for(auto tmp:u_mset1)
cout << tmp << ","; //4,9,5,3,3,2,1,
cout << endl;
return 0;
}
unordered_set 与 hash_set
unordered_set在C++11的时候被引入标准库了,而hash_set并没有,所以建议还是使用unordered_set比较好,
这就好比一个是官方认证的,一个是民间流传的。
889




被折叠的 条评论
为什么被折叠?



