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;
}
说明:利用比较函数,按比较函数比较的规则,来比较元素,辅助完成相关的工作。