C++map容器

map容器

#include <iostream>
#include <map>
#include <set>
#include <algorithm>


/*
 map 容器 关联式容器 python字典
 它的元素是 key - value 键值对 key键是唯一的 value值是可以重复的
 map中元素是按照key自动排序
 使用key访问
*/

// 使用函数模板
template <typename T1, typename T2>
void display(const std::map<T1, T2> &arr){
    // 打印 array 数组内的元素
    for (const auto &i: arr)
        std::cout << i.first << " " << i.second << " ";

    std::cout << std::endl;
};

void printmap(const std::map<std::string, std::set<int>> &m)
{
    for (const auto &i:m)
    {
        std::cout << i.first << " ";
        for (const auto &s : i.second)
            std::cout << s << " ";
    }

    std::cout << std::endl;
}


void test1()
{
    std::map<std::string, int> s1 {
        {"a3", 3},
        {"a2", 2},
        {"a1", 1},
    };
    display(s1);  // 自动根据key排序

    // 插入一个pair
    s1.insert( std::pair <std::string,int>("A1", 100) );
    display(s1);

    // 插入一个pair
    s1.insert(std::make_pair("B1", 200));
    display(s1);

    // 不存在-插入 或 存在-修改
    s1["AA"] = 300;   // 插入
    s1["AA"] = 200;   // 修改
    s1["AA"] += 300;  // 在原基础做运算 修改

    std::cout << "a1计数" << s1.count("a1") << std::endl;
    std::cout << "sm计数" << s1.count("sm") << std::endl;

    auto it = s1.find("a3"); // 迭代器 或者 end()
    if (it != s1.end())
        std::cout << "已找到" << it->first << " " <<  it->second<< std::endl;
    else
        std::cout << "未找到" << std::endl;

    s1.clear(); // 可以使用清空
}

void test2()
{
    std::map<std::string, std::set<int>> s1 {
        {"a3", {1, 2, 3}},
        {"a2", {22, 23, 24}},
        {"a1", {44, 45, 46}},
    };
    printmap(s1);

    s1["a5"].insert(80);       // 插入
    printmap(s1);

    auto it = s1.find("a1");   // 查找 指定元素
    if (it != s1.end())
    {
        it->second.erase(44);  // 删除 指定元素
    }
    printmap(s1);
     
}


int main()
{

    // test1();
    test2();
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

默执_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值