【STL】16 map容器操作补充

#include<iostream>
#include<map>
using namespace std;

class MyKey{
    public:
        int mIndex;
        int mID;
    public:
        MyKey(int index,int id):mIndex(index),mID(id){}
};

struct mycompare{
    bool operator()(MyKey key1,MyKey key2){
        return key1.mIndex > key2.mIndex;
    }
};

void test01(){
    //map将元素自动排序,但在自定义数据类型下需要添加排序条件  (这里的排序条件写的是mycompare) 
    map<MyKey,int,mycompare> mymap; 
    
    mymap.insert(make_pair(MyKey(1,2),10));
    mymap.insert(make_pair(MyKey(4,5),20));
    
    for(map<MyKey,int,mycompare>::iterator it = mymap.begin(); it != mymap.end();it++){
        cout<<it->first.mIndex<<":"<<it->first.mID<<"="<<it->second<<endl;
    }        
}

//equal_range 
void test02(){
    map<int,int> mymap; 
    mymap.insert(make_pair(1,4));
    mymap.insert(make_pair(2,5));
    mymap.insert(make_pair(3,6));
    
    pair<map<int,int>::iterator,map<int,int>::iterator> ret = mymap.equal_range(2);  //注意 pair 是运用 . 而不是 * 以及 -> 
    if(ret.first->second){
        cout<<"找到lower_bound! = "<<ret.first->first<<","<<ret.first->second<<endl;
    }
    else{
        cout<<"没有找到"<<endl;
    }
    if(ret.second->second){
        cout<<"找到upper_bound! = "<<ret.second->first<<","<<ret.second->second<<endl;
    }
    else{
        cout<<"没有找到"<<endl;
    }
} 
int main(){
    test01();
    test02();
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值