本文中的一些重要概念摘自C语言中文网
链接:http://c.biancheng.net/view/386.html
这次来学一下第一个关联容器multiset,它是排序好的集合,既然名字叫multi,那就意味着它是可以有重复元素的。还记得我在关联容器这一节中介绍的,multiset本身不允许修改元素的值,因为它并不会自动重新给multiset对象排序,如果修改了的话就会导致查找操作出现错误的结果。想要修改元素的值的正确做法是先删除这个元素,再插入一个新的元素。
使用 multiset 必须包含头文件 <set>。</set>
multiset的常用成员函数
multiset 及 set 中的 find 和 count 并不是用==运算符比较元素是否和待查找的值相等的。它们进行比较的原则是:如果x比y小和y比x小同时为假,就认为 x 和 y 相等。
最后附上我的简单的测试代码:
#include<iostream>
#include<set>
using namespace std;
template<class T>
void Print(T first, T last)
{
for(; first != last; ++first)
{
cout << *first << " ";
}
cout << endl;
}
int main()
{
int arr[] = {22, 33, 12, 50, 60, 84};
multiset<int> m1(arr, arr + 6);
multiset<int>::iterator i = m1.find(33);
if(i != m1.end())
{
cout << "found!" << endl;
}
cout << "init:";
Print(m1.begin(), m1.end());
m1.insert(arr, arr + 3);
cout << "after insert:";
Print(m1.begin(), m1.end());
cout << "count 22:" << m1.count(33) << endl;
multiset<int>::iterator j = m1.upper_bound(33);
m1.erase(m1.begin(), j);
cout << "after erase:";
Print(m1.begin(), m1.end());
return 0;
}输出结果:

京公网安备 11010502036488号