set相关操作总结(待续)

akcsdno 2020-04-23

//一些和vector,list类似的操作就没有总结#include <set>
#include <list>
#include <iostream>
using namespace std;

void count_set(const set<int> &set1, const set<int> &set2, const set<int>& set3)
{
    cout << "set1.size():" << set1.size() << ", set2.size():" << set2.size() << ", set3.size():" << set3.size() << endl;
}

//重载<<  使用场景对应"<< set4":"<<"对应ostream &os.
ostream& operator<<(ostream &os, const set<int>& setInt)
{
    for (set<int>::iterator itSet = setInt.begin(); itSet != setInt.end(); itSet++)
    {
        os << *itSet << " ";
    }
    return os;
}

int main()
{
    //底层结构是红黑树.
    /////////一.基础 /////////////
    //1.初始化和赋值
    set<int> set1 = {1,2,3,4,5,5};////发现这里不带=也是可以的,就相当于是int a (3)这样的初始化.
    set<int> set2;
    set<int> set3;
    set2 = set1;
    set3 = move(set1);
    count_set(set1, set2, set3);//0, 5, 5

    /////////五.查找 /////////////

    //1.count(key):返回匹配特定键的个数
    int nCount_0 = set3.count(0);
    cout << "0存在吗? " << boolalpha << bool(nCount_0) << endl;  //false
    //2.find(key):返回key所对应的迭代器,如果没有则返回end()有个cppreference上set的find的demo待理解后再整理.

    //3.low_bound(key):返回首个不小于key的元素对应的迭代器. 也就是以key作为下界,找到set中刚好为key或者key右边的.
    //4.upper_bound(key): !!!这个是返回首个大于key的迭代器.  左闭右开的原则. [LB,     UB)
    set<int> set4 = { 1,2,3,4,5,6,7,8};
    set<int>::iterator itLB = set4.lower_bound(3);
    set<int>::iterator itUB = set4.upper_bound(6);
    cout << *itLB << " " << *itUB << endl; //3, 7
    set4.erase(itLB, itUB);
    cout << set4 << endl; //1,2,7,8

    //5.equal_range(key):返回一个pair对,first是low_bound对应的值,second是upper_bound对应的值.
    
    //6.key_compare()/value_compare():返回该容器比较对象的副本.

    return 0;

}

//可参考网站:1.https://zh.cppreference.com/w/cpp/
//2.http://www.cplusplus.com/reference/

相关推荐