cpp的STL之map

cpp的STL之map

map/multimap

map key-value存储,可以理解为关联数组或者字典
multimap 运行一个key存储多个值

使用

//
//  main.cpp
//  use_stl_map
//
//  Created by bikang on 16/10/28.
//  Copyright (c) 2016年 bikang. All rights reserved.
//

#include <iostream>
#include <map>

using namespace std;

struct Test{

    bool operator ()(const int &a,const int &b) const{
        return (a < b);
    }

};


void tmap();

int main(int argc, const char * argv[]) {
    tmap();
    return 0;
}

void tmap(){
    cout << "test map" << endl;
    map<int, string> m1;
    multimap<int, string> mm1;

    //插入
    m1.insert(map<int, string>::value_type(1,"a"));
    m1.insert(map<int, string>::value_type(1,"aa"));
    m1.insert(map<int, string>::value_type(2,"b"));
    m1.insert(map<int, string>::value_type(3,"c"));
    m1.insert(pair<int, string>(4,"dd"));
    cout << "m1.size=" << m1.size() << endl;

    //访问元素
    cout << "m1[1]=" << m1[1]<< endl;

    //打印
    map<int, string>::iterator elem;

    for(elem=m1.begin();elem!=m1.end();++elem){
        cout << "key:" << elem->first<<",";
        cout << "value:" << elem->second;
        cout << endl;
    }

    //查找
    elem = m1.find(1);
    if(elem != m1.end()){
        cout << elem->first << "=>" << elem->second << endl;
    }else{
        cout << "find faild" << endl;
    }

    //删除
    //1 通过key删除  2 通过elem删除  3 通过边界删除

    m1.erase(1);
    m1.erase(m1.begin());

    for(elem=m1.begin();elem!=m1.end();++elem){
        cout << "key:" << elem->first<<",";
        cout << "value:" << elem->second;
        cout << endl;
    }

    //使用谓词 比较函数
    /**
     在C++中用到map时,如果KEY是自定义的struct,那么需要自己定义比较函数。因为只有基本类型有默认的比较方法。

     定义的方法有两种,一是在作为key的struct中,重载操作符less(<),二是自定义仿函数作为map的比较函数,个人比较喜欢第二种方法。
     **/
    map<int, int,Test> m11;

    m11.insert(pair<int, int>(1,1));
    m11.insert(pair<int, int>(2,2));
    m11.insert(pair<int, int>(3,3));
    m11.insert(pair<int, int>(4,4));

    cout << m11[1] << " " << m11[2]<<endl;
    cout << (m11[1] > m11[2]) <<  endl;

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值