C++ STL系列之:set

一、set介绍

set 集合,与map不同的就是它的key和value相同。

二、常用的函数

1 基本上都有的iterator

set::begin
set::end
set::rbegin //逆序的
set::rend
set::cbegin //返回 const_iterator
set::cend
set::crbegin //const_reverse_iterator
set::crend

2 常用的size empty之类

set::count
set::empty
set::clear
set::find
set::size
set::max_size
set::swap

set::emplace
set::erase
set::insert
set::emplace_hint

3 其他

set::get_allocator
set::operator=

set::equal_range
set::lower_bound
set::upper_bound
set::value_comp // 比较两个value在map中位置的先后,返回bool类型
set::key_comp   // 比较两个关键字在map中位置的先后

三、例子

#include <iostream>
#include <set>

using namespace std;

class good {
public:
    int key;
    good(int k):key(k){}

//#if 0
    inline bool operator<(const good& __x) const{
        return this->key < __x.key;
    }
//#endif

};

#if 0
bool operator<(const good& __x, const good& __y){
    return __x.key < __y.key;
}
#endif

class comp{

public:
    inline bool operator()(const good& l, const good& r) const{
        return l.key > r.key; // from big to small
    }
};


int main()
{
    int a[5] = {5,2,10,3,7};

    set<int> myset(a,a+5);

    for(set<int>::iterator it = myset.begin(); it != myset.end(); ++it){
        cout<<*it<<"\t";
    }
    cout<<endl;

    good g1(a[0]);
    good g2(a[1]);
    good g3(3);
    good g4(1);
    good g5(4);

    set<good, comp> myset2;
    myset2.insert(g1);
    myset2.insert(g2);
    myset2.insert(g3);
    myset2.insert(g4);

    for(set<good>::iterator it = myset2.begin(); it != myset2.end(); ++it){
        cout<<(*it).key<<"\t";
    }
    cout<<endl;


    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值