set查找和统计示例

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

int main() {
    set<int> data = {10, 20, 30, 40, 50, 60, 70, 80, 90, 100};
    
    cout << "=== 查找操作详解 ===" << endl;
    
    // 1. find() - 精确查找
    auto it = data.find(50);
    if(it != data.end()) {
        cout << "找到50: " << *it << endl;
    } else {
        cout << "未找到50" << endl;
    }
    
    // 查找不存在的元素
    it = data.find(55);
    if(it == data.end()) {
        cout << "未找到55" << endl;
    }
    
    // 2. count() - 统计出现次数(set中只能是0或1)
    cout << "50出现次数: " << data.count(50) << endl;
    cout << "55出现次数: " << data.count(55) << endl;
    
    // 3. contains() - C++20 检查包含关系
    // if(data.contains(60)) { cout << "包含60" << endl; }
    
    cout << "\n=== 边界查找 ===" << endl;
    
    // 4. lower_bound() - 第一个 >= 的值
    // 5. upper_bound() - 第一个 > 的值
    // 6. equal_range() - [lower_bound, upper_bound) 的范围
    
    int searchValue = 45;
    auto lower = data.lower_bound(searchValue);
    auto upper = data.upper_bound(searchValue);
    
    cout << "搜索值: " << searchValue << endl;
    if(lower != data.end()) {
        cout << "lower_bound: " << *lower << " (第一个>=45的值)" << endl;
    }
    if(upper != data.end()) {
        cout << "upper_bound: " << *upper << " (第一个>45的值)" << endl;
    }
    
    // 使用边界查找实现范围查询
    cout << "\n范围查询 [30, 70]:" << endl;
    auto range_start = data.lower_bound(30);
    auto range_end = data.upper_bound(70);
    
    for(auto it = range_start; it != range_end; ++it) {
        cout << *it << " ";
    }
    cout << endl;
    
    return 0;
}

 

posted @ 2025-10-08 11:31  爱吃泡面的皮卡  阅读(6)  评论(0)    收藏  举报