Multiset多重集合容器

Multiset多重集合容器

一、基本原理

同set,只是允许插入重复元素。插入函数不再用insert_unique了,而是用insert_equal。

二、应用

1、插入

iterator insert(iterator position, const value_type& x);

iterator insert(const value_type& x);

2、元素的搜索

const_iterator find(const Key& key) const;

3、创建

multiset(const value_type *first, const value_type *last,const Pred& comp = 

Pred(), const A& al = A());

第三个是比较函数,第四个是内存创建模型,可以省略。

pair<const_iterator, const_iterator>equal_range(const Key& key) const;

4、计数

size_type count(const Key& key) const;

The member function returns the number of elements x in the range [lower_

bound(key), upper_bound(key)).

const_iterator lower_bound(const Key& key) const;

The member function returns an iterator that designates the earliest element 

x in the controlled sequence for which key_comp()(x, key) is false.If no 

such element exists, the function returns end(). 

const_iterator upper_bound(const Key& key) const;

The member function returns an iterator that designates the earliest element 

x in the controlled sequence for which key_comp()(key, x) is true.If no such 

element exists, the function returns end(). 

key_compare key_comp() const;

The member function returns the stored function object that determines the 

order of elements in the controlled sequence. The stored object defines the 

member function:

bool operator(const Key& x, const Key& y);//默认的是Less关系

which returns true if x strictly precedes y in the sort order.

typedef Pred key_compare;

5、其它

其它操作函数类同set。可参见set,也可看MSDN。

三、举例

#include "set"

#include "iostream"

using namespace std;

struct Student{

char* name;

int year;

};

struct StudentLess{

bool operator()(const Student& s1,const Student& s2) const

  {

   return s1.year<s2.year;

  }

};

int main()

{

Student stuArray[]={

    {"I",3},

 {"You",1},

 {"He",2},

 {"Youy",2}

};

multiset<Student,StudentLess> ms(stuArray,stuArray+4,StudentLess());

cout<<"学生人数:"<<ms.size()<<endl;//4

cout<<"年龄为岁的学生人数:"<<ms.count(stuArray[2])<<endl;//2

multiset<Student,StudentLess>::iterator i;

cout<<"Name  "<<"Age  "<<endl;

for(i=ms.begin();i!=ms.end();i++){

cout<<(*i).name<<"  "<<(*i).year<<endl;//已经排序了

}

cout<<endl;

return 1;

}

说明:利用比较函数,按比较函数比较的规则,来比较元素,辅助完成相关的工作。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值