STL map学习小记

map 键值对,一对一,会自动排序,底层数据结构是红黑树,查找、插入、删除某一元素贼快,因为其不是线性数据结构,故不能用sort函数。

#include<iostream>
#include<map>
#include<algorithm>
#include<string>
using namespace std;
int main()
{
    map<int,int,greater<int> > a;  //默认从小到大排序  greater从大到小排序
    int i,j,n,m,t,k;
    cin>>n;
    
    //增添 
    for(i=0;i<n;i++)
    {
        cin>>m>>k;
        a.insert(make_pair(m,k));
    }
    cin>>k;
    a[n]=k;
    
    //查找 
    if(a.count(n))
    cout<<"wo find n!"<<endl;
    else
    cout<<"Sorry,wo didn't find!"<<endl;
    map<int,int>::iterator it;
    it=a.find(99);
    if(it==a.end())
    cout<<"Sorry,wo didn't find"<<endl;
    else
    cout<<"wo find!"<<endl;
    
    //遍历 
    map<int,int>::iterator id=a.begin();
    for(;id!=a.end();id++)
    cout<<id->first<<"  "<<id->second<<endl;
    map<int,int>::reverse_iterator is=a.rbegin();
    for(;is!=a.rend();is++)
    cout<<is->first<<" "<<is->second<<endl;
    
    //删除 
    a.erase(n);//括号里的内容可以是迭代器,亦可以是键
    a.clear(); 
    return 0;

map里亦可以是结构体,但对结构体进行特定排序

请看:

https://blog.csdn.net/qq_41325698/article/details/81569393

思路:就是讲结构体赋值给vector,对vector进行特殊排序

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值