set容器查找操作使用

对于set容器来说,查找功能是该容器的主要优势,故针对该容器查找功能作一测试。

主要有如下API接口:

测试源码如下:

#include<set>
void test(){
    set<int> myset;
    myset.insert(10);
    myset.insert(5);
    myset.insert(1);
    myset.insert(8);
    //查找键key是否存在,返回改键元素的迭代器;若不存在,返回map.end();
    set<int>::iterator pos = myset.find(2);  
    if (pos == myset.end()) {
        cout << "没有找到!" << endl;
    }
    else {
        cout << "找到:" << *pos << endl;
    }
    //返回第一个key>=keyElem元素的迭代器
    pos = myset.lower_bound(5);  
    if (pos == myset.end()){
        cout << "没有找到!" << endl;
    }
    else{
        cout << "找到:" << *pos << endl;
    }
    //返回第一个key>keyElem元素的迭代器
    pos = myset.upper_bound(5);
    if (pos == myset.end()){
        cout << "没有找到!" << endl;
    }
    else{
        cout << "找到:" << *pos << endl;
    }
    //返回容器中key与keyElem相等的上下限的两个迭代器
    //equal_range()可以返回lower_bound()和upper_bound()的值
    pair<set<int>::iterator, set<int>::iterator> pos2 =  myset.equal_range(5);
    if (pos2.first == myset.end()){
        cout << "没找到!" << endl;
    }
    else{
        cout << "equal_range找到:" << *(pos2.first) << endl;
    }

    if (pos2.second == myset.end()){
        cout << "没找到!" << endl;
    }
    else {
        cout << "equal_range找到:" << *(pos2.second) << endl;
    }

}

运行结果:

 

posted @ 2019-04-24 18:26  鲸小鱼-  阅读(550)  评论(0编辑  收藏  举报