stl map常用函数

    //构造函数
    //map()
    map<char, int> m1;

    //指定一个比较函数来创建map对象
    struct KeyCompare
    {
        bool operator()(const char* s1, const char* s2) const
        {
            return strcmp(s1, s2) < 0;
        }
    };
    map<const char*, int, KeyCompare> m2;

    //map(const _Myt& _Right)
    map<const char*, int, KeyCompare> m3(m2);

    //map(_Iter _First, _Iter _Last)
    pair<int, char> p1(1, 'a');
    pair<int, char> p2(2, 'b');
    pair<int, char> p3(3, 'c');
    pair<int, char> arr[] = { p1, p2, p3 };
    map<int, char> m4(arr, arr + 3);

    //插入元素
    pair<map<int, char>::iterator, bool> bRet = m4.insert(make_pair(4, 'd'));
    if (bRet.second)
    {
        cout << "insert success" << endl;
    }
    else
    {
        cout << "insert failed" << endl;
    }

    //在可能的位置之前插入元素
    pair<int, char> p5(5, 'e');
    map<int, char>::iterator i = m4.insert(m4.begin(), p5);

    //插入区间元素
    map<int, char> m5;
    m5.insert(m4.begin(), m4.end());
    map<int, char>::iterator iter;
    for (iter = m5.begin(); iter != m5.end(); ++iter)
    {
        cout << iter->first << " " << iter->second << endl;
    }
    cout << endl;
    //1 a
    //2 b
    //3 c
    //4 d
    //5 e
    map<int, char>::reverse_iterator rIter;
    for (rIter = m5.rbegin(); rIter != m5.rend(); ++rIter)
    {
        cout << rIter->first << " " << rIter->second << endl;
    }
    cout << endl;

    map<int, char>::iterator rFind = m5.find(3);
    if (rFind == m5.end())
    {
        cout << "not found" << endl;
    }
    else
    {
        int i = 0;
        iter = m5.begin();
        while (iter != rFind)
        {
            ++i;
            ++iter;
        }
        cout << "find index:" << i << endl;
    }

    //删除元素
    m4.erase(m4.begin());
    //删除键值33的元素
    m4.erase(33);
    //删除区间元素
    m4.erase(m4.begin(), ++m4.begin());
    //删除所有元素
    m4.clear();

    //容器是否为空
    bool b = m4.empty();

    //实际元素个数
    size_t count = m4.size();

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值