有序关联容器

本文详细介绍了如何使用C++ STL中的set和map数据结构,包括向set中插入int类型及自定义类型数据,并实现自定义类型的比较运算符以支持排序。同时,展示了如何向map中插入键值对,以及遍历和输出map中的元素。

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

头文件:
#inlucde
#include
底层数据结构:红黑树

向有序set集合中放入int类型的数据

#include <iostream>
#include <set>
#include <map>
using namespace std;
int main()
{
    set<int> set;
    for (int i = 0; i < 20; ++i)
    {
        set.insert(rand() % 20 + 1);
    }
    for (int v : set)
    {
        cout << v << " ";
    }
    cout << endl;
}

在这里插入图片描述

向有序set集合中放入用户自定义类型的数据

#include <iostream>
#include <set>
#include <map>
using namespace std;
class Student
{
public:
    Student(int id, string name) :_id(id), _name(name) {}
    bool operator<(const Student &stu)const
    {
        return   _id < stu._id;
    }
private:
    int _id;
    string _name;
    friend ostream& operator<<(ostream& out, const Student& stu);
};
ostream& operator<<(ostream& out, const Student& stu)
{
    out << "id: " << stu._id << "name: " << stu._name << endl;
    return out;
}

int main()
{
    set<Student> set;
    set.insert(Student(2020,"张嘉文"));
    set.insert(Student(2021, "李乐"));
    set.insert(Student(2022, "无言"));
    for (auto it = set.begin(); it != set.end(); ++it)
    {
        cout << *it << endl;
    }
    return 0;
}

向有序map映射表中放入数据:

class Student
{
public:
    Student(int id = 0, string name = " ") :_id(id), _name(name) {}
private:
    int _id;
    string _name;
    friend ostream& operator<<(ostream& out, const Student& stu);
};
ostream& operator<<(ostream& out, const Student& stu)
{
    out << "id: " << stu._id << " name: " << stu._name << endl;
    return out;
}

int main()
{
    map<int, Student> stumap;
    stumap.insert({ 2020, Student(2020,"张嘉文" )});
    stumap.insert({ 2000, Student(2000,"李光") });
    stumap.insert({ 2030, Student(2030,"无言") });
    for (auto it = stumap.begin(); it != stumap.end(); ++it)
    {
        //stumap.erase(it)  stumap.erase(key)
        cout << "key: " << it->first << " value: " << it->second << " ";
    }
   // cout << stumap[2020] << endl;
    cout << endl;
}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值