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 @   鲸小鱼-  阅读(563)  评论(0编辑  收藏  举报
编辑推荐:
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· C#/.NET/.NET Core技术前沿周刊 | 第 29 期(2025年3.1-3.9)
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
点击右上角即可分享
微信分享提示