1. 简介
multiset是一种关联式容器,包含一组经过排序后的key值,与set不同,其key允许重复;增加、修改和查询具有对数的时间复杂度,其存储结构为红黑树;
头文件和定义
#include <set>
template<
class Key,
class Compare = std::less<Key>,
class Allocator = std::allocator<Key>
> class multiset;
2. 初始化
初始化的方法如下所示
#include <iostream>
#include <set>
#include <string>
template<typename T>
void showInfo(T &t)
{
for(auto &au : t)
{
std::cout<<au<<" ";
}
std::cout<<std::endl;
}
int main(int argc, char *argv[])
{
std::multiset<std::string> ms1;
ms1.emplace("c++");
ms1.emplace("c++");
ms1.emplace("c");
showInfo(ms1);
std::multiset<std::string> ms2{
"linux", "matlab", "java", "js", "linux", "java"};
showInfo(ms2);
std::multiset<std::string> ms3 = ms1;
showInfo(ms3);
return 0;
}
输出
c c++ c++
java java js linux linux matlab
c c++ c++
3. 使用
其支持的操作与set一样;
但是相比与set,像count()就有了用武之地;find()是查找第一个元素出现的时间;
int main(int argc, char *argv[])
{
std::multiset<std::string> ms1;
ms1.emplace("c++");
ms1.emplace("c++");
ms1.emplace("c");
showInfo(ms1);
std::cout<<"the number of c++ is: "<<ms1.count("c++")<<"\n\n";
auto au = ms1.find("c++");
std::cout<<*au<<std::endl;
std::cout<<"the location of au to end is: "<<std::distance(au, ms1.end())<<"\n";
std::cout<<"the location of begin to end is: "<<std::distance(ms1.begin(), ms1.end())<<"\n";
return 0;
}
输出
c c++ c++
the number of c++ is: 2
c++
the location of au to end is: 2
the location of begin to end is: 3