STL 小白学习(8) set 二叉树

#include <iostream>
using namespace std;
#include <set>


void printSet(set<int> s) {
    for (set<int>::iterator it = s.begin(); it != s.end(); it++) {
        cout << *it << " ";
    }
    cout << endl;
}
//初始化
void test01(){
    set<int> s1;//初始化
    s1.insert(1);
    s1.insert(65);
    s1.insert(4);
    s1.insert(23);
    s1.insert(234);
    s1.insert(2);
    printSet(s1);//默认从小到大排序

    //改变默认排序

}
//赋值操作
//等号重载 swap clear empty略
void test02() {
    set<int> s1;//初始化
    s1.insert(1);
    s1.insert(65);
    s1.insert(4);
    s1.insert(23);
    s1.insert(234);
    s1.insert(2);

    s1.erase(s1.begin());//根据迭代器位置进行删除
    s1.erase(2);//删除指定元素
    printSet(s1);
    s1.erase(s1.begin(),s1.end());//根据迭代器位置进行删除
    printSet(s1);
}
//查找操作
void test03() {
    set<int> s1;
    s1.insert(14);
    s1.insert(15);
    s1.insert(16);
    set<int>::iterator ret = s1.find(14); //find() 返回迭代器 没找到返回s1.end()
    if (ret == s1.end()) {
        cout << "没有找到!" << endl;
    }
    else {
        cout << "找到" << *ret << endl;
    }
    set<int>::iterator ret2 = s1.find(44); //find() 返回迭代器 没找到返回s1.end()
    if (ret2 == s1.end()) {
        cout << "没有找到!" << endl;
    }
    else {
        cout << "找到" << *ret << endl;
    }

    //lower_bound(keyElem) 存在keyElem返回迭代器 不存在 则返回最小的大于keyElem的迭代器
    ret = s1.lower_bound(14);
    if (ret == s1.end()) {
        cout << "没有找到!" << endl;
    }
    else {
        cout << "找到" << *ret << endl;
    }

    ret = s1.lower_bound(12);//查找12 没有12 返回最小的大于12的元素的迭代器
    if (ret == s1.end()) {
        cout << "没有找到!" << endl;
    }
    else {
        cout << "找到" << *ret << endl;
    }

    //upper_bound(keyElem)  返回最小的大于keyElem的迭代器 不找keyElem
    ret = s1.upper_bound(14);
    if (ret == s1.end()) {
        cout << "没有找到!" << endl;
    }
    else {
        cout << "找到" << *ret << endl;
    }
    
    

}

//equal_range
void test04() {
    set<int> s1 = { 9,485,547,3234,15647,1564 };
    //equal_range 返回Lower_bound 和 upper_bound 的值
    pair<set<int>::iterator, set<int>::iterator> myret = s1.equal_range(485);//pair
    myret.first;//Lower_bound
    myret.second;//upper_bound
    if (myret.first == s1.end()) {
        cout << "没有找到!" << endl;
    }
    else {
        cout << "找到" << *myret.first << endl;
    }
    if (myret.second == s1.end()) {
        cout << "没有找到!" << endl;
    }
    else {
        cout << "找到" << *myret.second << endl;
    }
}







int main() {
    test04();
}
原文地址:https://www.cnblogs.com/likeghee/p/10180685.html