stl set 使用结构体

本文介绍了一个使用C++实现的自定义排序规则的例子。通过定义一个结构体并在其中重载小于运算符来实现对包含整数ID和字符串数据的包进行排序。示例展示了如何创建并初始化结构体,以及如何将这些包插入到集合中,并遍历打印集合中的所有元素。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

struct package
{
    int id;
    string data;
    bool operator<(const package& tmp) const{
        if(this->id < tmp.id)
            return true;   //自定义排序规则
        return false;
    }
};

int main() {
    set<package> tmp;
    tmp.insert({3,"a"});
    tmp.insert({2,"b"});  //插入
    set<package>::iterator i;
    for(i = tmp.begin(); i != tmp.end(); i++)
        cout << i->id << " " << i->data << endl;
}
在C++的STL库中,set是一种有序的容器,它使用红黑树实现。由于set是有序的,所以可以使用二分查找算法在set结构体中查找元素。 在C++中,使用STL库的set结构体进行二分查找可以通过调用set的成员函数lower_bound()实现。lower_bound()函数返回一个迭代器,该迭代器指向第一个不小于指定值的元素。如果找不到这样的元素,lower_bound()函数将返回迭代器指向set的end()位置。 以下是使用set结构体进行二分查找的代码示例: ``` #include <iostream> #include <set> int main() { std::set<int> mySet = {1, 2, 3, 4, 5, 6, 7, 8}; int target1 = 0; auto it1 = mySet.lower_bound(target1); if (it1 != mySet.end() && *it1 == target1) { std::cout << "Element " << target1 << " found at position " << std::distance(mySet.begin(), it1) << std::endl; } else { std::cout << "Element " << target1 << " not found in the set." << std::endl; } int target2 = 6; auto it2 = mySet.lower_bound(target2); if (it2 != mySet.end() && *it2 == target2) { std::cout << "Element " << target2 << " found at position " << std::distance(mySet.begin(), it2) << std::endl; } else { std::cout << "Element " << target2 << " not found in the set." << std::endl; } int target3 = 111; auto it3 = mySet.lower_bound(target3); if (it3 != mySet.end() && *it3 == target3) { std::cout << "Element " << target3 << " found at position " << std::distance(mySet.begin(), it3) << std::endl; } else { std::cout << "Element " << target3 << " not found in the set." << std::endl; } return 0; } ``` 请注意,为了使用set结构体进行二分查找,你需要在程序中包含头文件<set>。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值