STL set 详细用法

一个集合(set)是一个容器,它其中所包含的元素的值是唯一的。

用到的库

#include <set>

定义

最简单:

set<int> a;

set和其他的stl一样,都支持自定义。

因为set会自动将元素从小到大排序,所以我们可以设定它的比较函数,这里与优先队列十分相似。

法1 利用自定义比较函数:

#include<stdio.h>
#include<set>
#include<string>
using namespace std;
struct People
{
    string name;
    int age;
};

struct cmp {
    bool operator  ()(People a, People b)
    {
        if(a.name==b.name)return false;
        return a.age<b.age;       //按照年龄由小到大进行排序
    }
};
 

set<People,cmp>s;

法2 运算符重载

#include<stdio.h>
#include<set>
#include<string>
using namespace std;
struct People
{
    string name;
    int age;
    bool operator <(const People p) const  //运算符重载
    {
        if(name==p.name)return false;//按名字去重
        return age<p.age;       //按照年龄由小到大进行排序
    }
 
};

set<People>s;

法3 友元函数

#include<bits/stdc++.h>

using namespace std;

struct People
{
    string name;
    int age;
    friend bool operator <(const People & a,const  People & b)
    {
        if(a.name==b.name)return false;//按名字去重
        return a.age<b.age;       //按照年龄由小到大进行排序
    }
 
};

set<People>s;

遍历

也是需要一个迭代器进行访问:

set<People>::iterator it;
for(it=s.begin();it!=s.end();it++)  
{
    printf("姓名:%s 年龄:%d\n",(*it).name.c_str(),(*it).age);
}

访问set的值需要采用*t的方式。

其他用法:

begin();                        第一个元素地址
clear();                         清楚set容器
count(x);                      x元素的个数
empty();                       是否为空
end();                           最后一个元素后面一个的地址
erase(x);                      删除元素x
find(x);                         查找元素x,返回地址,若没有则返回end
insert(x);                      增加元素x
size();                           元素个数

猜你喜欢

转载自www.cnblogs.com/dyhaohaoxuexi/p/11324742.html
今日推荐