C++容器——集合(multiset)

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
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值