在STL中,set和multiset都是关联容器,内部元素是有序的,内部实现基于红黑树。
红黑树通过把节点分为红黑两个颜色并根据一些规则确保树在一定程度上是平衡的,从而确保在红黑树中查找,删除,插入都只需要O(logn)时间。
set和multiset的区别是multiset中的元素是可以重复的。
1. 内部元素顺序可以自定义。
multiset中元素默认是升序排列的,声明如multiset<int, greater<int>>
如果需要降序排列需要增加参数,如multiset<int, greater<int>>
#include <iostream>
#include <vector>
#include <set>
using namespace std;
int main()
{
vector<int> input = {4,5,1,6,2,7,3,8,8};
multiset<int, greater<int>> downSet;
for(vector<int>::iterator it = input.begin(); it != input.end(); it++)
{
downSet.insert(*it);
}
cout << "downSet:" << endl;
for(multiset<int, greater<int>>::iterator it = downSet.begin(); it != downSet.end(); it++)
{
cout << *it << " ";
}
cout << endl;
cout << endl;
multiset<int> upSet;
for(vector<int>::iterator it = input.begin(); it != input.end(); it++)
{
upSet.insert(*it);
}
cout << "upSet:" << endl;
for(multiset<int>::iterator it = upSet.begin(); it != upSet.end(); it++)
{
cout << *it << " ";
}
cout << endl;
}
output:
2. 删除。
c.erase(val); //移除与val相等的所有元素,返回被移除的元素个数 c.erase(pos); //移除iterator位置pos上的元素,无返回值
erase(it)时只删除了第一个8, 但是erase(8)时会把所有的8全部删除掉。
#include <iostream>
#include <vector>
#include <set>
using namespace std;
int main()
{
vector<int> input = {4,5,1,6,2,7,3,8,8,8,8};
multiset<int, greater<int>> downSet;
for(vector<int>::iterator it = input.begin(); it != input.end(); it++)
{
downSet.insert(*it);
}
cout << "downSet:" << endl;
for(multiset<int, greater<int>>::iterator it = downSet.begin(); it != downSet.end(); it++)
{
cout << *it << " ";
}
cout << endl;
cout << endl;
multiset<int, greater<int>>::iterator it = downSet.begin();
downSet.erase(it);
cout << "downSet.erase(it):" << endl;
for(multiset<int, greater<int>>::iterator it = downSet.begin(); it != downSet.end(); it++)
{
cout << *it << " ";
}
cout << endl;
cout << endl;
downSet.erase(8);
cout << "downSet.erase(8):" << endl;
for(multiset<int, greater<int>>::iterator it = downSet.begin(); it != downSet.end(); it++)
{
cout << *it << " ";
}
cout << endl;
}
output: