1. 简介
unordered_multiset是一种关联式容器,其key值允许重复;增加、修改和查询具有线性的时间复杂度,其存储结构为哈希表;元素的存储并未按照特定的顺序,而是被组织到桶中,在哪个桶中取决于其散列值;
头文件和定义
#include <unordered_set>
template<
class Key,
class Hash = std::hash<Key>,
class KeyEqual = std::equal_to<Key>,
class Allocator = std::allocator<Key>
> class unordered_multiset;
2. 初始化
unordered_multiset 的初始化如下所示
/*
* @brief unordered_multiset
* @g++ -g unordered_multiset_main.cc -o d -std=c++11
* @author
* @date 2023/03/27
*/
#include <iostream>
#include <unordered_set>
#include <string>
#include <iterator>
template<typename T>
void showInfo(T& t)
{
for(const auto& au : t)
{
std::cout<<au<<" ";
}
std::cout<<std::endl;
}
int main(int argc, char* argv[])
{
//直接初始化
std::unordered_multiset<std::string> un_s1{"c++", "c", "Rust", "golang", "Rust","Rust","linux", "matlab"};
showInfo(un_s1);
std::unordered_multiset<std::string> un_s2;
un_s2.emplace("student");
un_s2.emplace("student");
un_s2.insert("teacher");
un_s2.insert("teacher");
//拷贝初始化
std::unordered_multiset<std::string> un_s3 = un_s2;
showInfo(un_s3);
return 0;
}
输出
linux golang Rust Rust Rust matlab c c++
teacher teacher student student
3. 使用
其支持的操作和unordered_set一致;
不过对于count()、find()、equal_range()等方法,unordered_multiset起的作用更大
示例
int main(int argc, char* argv[])
{
//操作 count() find() equal_range()
std::unordered_multiset<std::string> un_s1{"c++", "c", "Rust", "golang", "Rust","Rust","linux", "matlab"};
showInfo(un_s1);
std::cout<<"\ncount() of Rust is: "<<un_s1.count("Rust")<<"\n\n";
std::cout<<"[find() test]\n";
auto iter = un_s1.find("Rust");
std::cout<<*iter<<std::endl;
std::advance(iter, 1);
std::cout<<*iter<<std::endl;
std::advance(iter, 1);
std::cout<<*iter<<std::endl<<std::endl;
std::cout<<"[equal_range() test]\n";
auto iter_equal = un_s1.equal_range("Rust");
std::cout<<std::distance(iter_equal.first,iter_equal.second)<<"\n";
while (iter_equal.first != iter_equal.second)
{
std::cout<<*iter_equal.first<<" ";
std::advance(iter_equal.first, 1);
}
std::cout<<std::endl;
return 0;
}
结果
linux golang Rust Rust Rust matlab c c++
count() of Rust is: 3
[find() test]
Rust
Rust
Rust
[equal_range() test]
3
Rust Rust Rust