STL之set和multiset(集合)

本文详细介绍了C++ STL中set和multiset容器的使用方法,包括构造、插入、删除元素以及如何使用count函数计数重复元素。通过实例代码展示了set自动排序的特点及其与multiset的区别。
set和multiset会根据特定的排序准则,自动将元素进行排序。不同的是后者允许元素重复而前者不允许。 constructing sets

#include
#include
using namespace std ;
int main()  {
    int a[] = {2,1,3,4,5,6,8,7} ;
    set s(a,a+8) ;
    set::iterator iter = s.begin() ;
    for( ; iter != s.end() ; iter++)
        cout << *iter << " " ;
    cout << endl ;
    return 0 ;
}
向对象中插入元素:

#include
#include
using namespace std ;
int main()  {
    set s;
    int a[] = {2,1,3,4,5,6,8,7} ;
    for(int i = 0 ; i < 8 ; i++)
        s.insert(a[i]) ;
    set::iterator iter = s.begin() ;
    for( ; iter != s.end() ; iter++)
        cout << *iter << " " ;
    cout << endl ;
    return 0 ;
}
删除对象中的元素:

#include
#include
using namespace std ;
int main()  {
    int a[] = {2,1,3,4,5,6,8,7} ;
    set s(a,a+8);

    s.erase(s.begin()) ;
    set::iterator iter = s.begin() ;
    for( ; iter != s.end() ; iter++)
        cout << *iter << " " ;
    cout << endl ;

    s.erase(s.find(8)) ;
    set::iterator iter1 = s.begin() ;
    for( ; iter1 != s.end() ; iter1++)
        cout << *iter1 << " " ;
    cout << endl ;

    s.erase(s.begin(),s.end()) ;
    set::iterator iter2 = s.begin() ;
    for( ; iter2 != s.end() ; iter2++)
        cout << *iter2 << " " ;
    cout << endl ;
    return 0 ;
}
count计数函数:

#include
#include
using namespace std ;
int main()  {
    int a[] = {2,1,3,4,5,6,8,7,8,8} ;   //multiet允许元素重复
    multiset s(a,a+10);
    cout << s.count(8) << endl ;
    return 0 ;
}

转载于:https://www.cnblogs.com/NYNU-ACM/p/4236861.html

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值