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;

STL map学习小记

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

请看:

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

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

 

相关文章:

  • 2021-10-28
  • 2021-12-30
  • 2021-11-18
  • 2022-01-20
  • 2022-12-23
  • 2021-08-01
  • 2021-10-26
  • 2021-08-01
猜你喜欢
  • 2021-10-07
  • 2022-12-23
  • 2022-02-24
  • 2022-02-17
  • 2022-12-23
  • 2021-07-08
  • 2021-08-31
相关资源
相似解决方案