STL-map/multimap

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

using namespace std;

void printMap(const map<int, int> &m)
{
    for (map<int, int>::const_iterator it = m.begin(); it != m.end(); ++it)
        cout << "key = " << it->first << ", value = " << it->second << endl;
}

void test01()
{
    //构造
    map<int, int> m1{{1, 10}, {2, 20}, {3, 30}};
    printMap(m1);
    map<int, int> m2(m1);
    printMap(m2);
    map<int, int> m3 = m1;
    printMap(m3);
}

void test02()
{
    map<int, int> m1{{1, 10}, {2, 20}, {3, 30}};
    if (m1.empty())
    {
        cout << "m1为空!" << endl;
    }
    else
    {
        cout << "m1不为空,大小为" << m1.size() << endl;
        for_each(m1.begin(), m1.end(), [&](const pair<int, int> &p) {
            cout << "key = " << p.first << ", value = " << p.second << endl;
        });
    }

    //交换
    map<int, int> m2{{4, 40}, {5, 50}, {6, 60}};
    m1.swap(m2);
    cout << "交换后" << endl;
    printMap(m1);
}

void test03()
{
    map<int, char> m1;
    m1.insert(pair<int, char>(0, 'a'));
    m1.insert(make_pair(1, 'b'));
    m1.insert(map<int, char>::value_type(2, 'c'));
    m1[3] = 'd';
    for_each(m1.begin(), m1.end(), [&](const pair<int, char> p) {
        cout << "key = " << p.first << ", value = " << p.second << endl;
    });

    //删除
    m1.erase(m1.begin());
    m1.erase(2);
    for_each(m1.begin(), m1.end(), [&](const pair<int, char> p) {
        cout << "key = " << p.first << ", value = " << p.second << endl;
    });

    map<int, char>::iterator pos = m1.find(3);
    if (pos == m1.end())
    {
        cout << "未找到元素" << endl;
    }
    else
    {
        int num = m1.count(3);
        cout << "找到了元素key = " << pos->first << ", value = " << pos->second \
             << ", 该元素有" << num << "个" << endl;
    }

    //清空
    //m1.erase(m1.begin(), m1.end());
    m1.clear();
}

int main(int argc, char const *argv[])
{
    /*1. map中所有元素都是pair,pair中第一个元素是key(键值),起到索引作用,第二个元素是value(实值)
    2. 所有元素都会根据元素的键值自动排序
    3. 优点:可以根据key值快速找到value值
    4. map不允许容器中有重复的key值元素,multimap允许容器中有重复key值元素*/

    //构造
    test01();

    //大小和交换
    test02();

    //插入和删除
    test03();

    return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值