map的用法大全

map是STL的一个关联容器,它提供一对一(其中第一个可以称为关键字,每个关键字只能在map中出现一次,第二个可能称为该关键字的值)的数据处理能力,由于这个特性,它完成有可能在我们处理一对一数据的时候,在编程上提供快速通道。这里说下map内部数据的组织,map内部自建一颗红黑树(一种非严格意义上的平衡二叉树),这颗树具有对数据自动排序的功能,所以在map内部所有的数据都是有序的。

1,数据的插入

map<int,int> m;
m.insert({1,2});
auto it = m.find(1);
if(it != m.end()){
    cout << it->first << " " << it->second;
}

2,map的大小

int msize = m.size();

3,数据的遍历

正向:

map<int,int> m;
int n;cin >> n;
for(int i = 1; i <= n; i++){
    cin >> m[i];
}
map<int,int>::iterator it;
for(it = m.begin(); it != m.end(); it++){
    cout << it->first << " " << it->second << "\n";
}

反向:

map<int,int> m;
int n;cin >> n;
for(int i = 1; i <= n; i++){
    cin >> m[i];
}
map<int,int>::reverse_iterator it;
for(it = m.rbegin(); it != m.rend(); it++){
    cout << it->first << " " << it->second << "\n";
}

4,数据的查找

(1)用count函数来判断关键字是否出现,但是无法判断出现位置,count函数的返回值只有0,1,出现返回1。

(2)用find函数来定位数据出现位置,它返回一个迭代器,如果没有找到则返回它的迭代器等于end函数返回的迭代器。

#include <bits/stdc++.h>
using namespace std;

int main()
{
    map<int,int> m;
    int n;cin >> n;
    for(int i = 1; i <= n; i++){
        cin >> m[i];
    }
    cout << m.count(1);

    auto it = m.find(1);
    if(it != m.end()){
        cout << it->first << " " << it->second << "\n";
    }
    else{
        cout << "no find\n";
    }
    return 0;

}

(3)利用Lower_bound和Upper_bound函数

Lower_bound函数用法,这个函数用来返回要查找关键字的下界(是一个迭代器)

Upper_bound函数用法,这个函数用来返回要查找关键字的上界(是一个迭代器)

例如:map中已经插入了1,2,3,4的话,如果lower_bound(2)的话,返回的2,而upper-bound(2)的话,返回的就是3

#include <bits/stdc++.h>
using namespace std;

int main()
{
    map<int,int> m;
    int n;cin >> n;
    for(int i = 1; i <= n; i++){
        cin >> m[i];
    }
    auto it1 = m.lower_bound(2);
    auto it2 = m.upper_bound(2);
    cout << it1->first << " " << it1->second << endl;
    cout << it2->first << " " << it2->second << endl;
    return 0;
    5
    7 4 2 5 3
    2 4
    3 2

}

5,数据的清空与判空

清空map中的数据可以用clear()函数,判定map中是否有数据可以用empty()函数,它返回true则说明是空map。

#include <bits/stdc++.h>
using namespace std;

int main()
{
    map<int,int> m;
    int n;cin >> n;
    for(int i = 1; i <= n; i++){
        cin >> m[i];
    }
    auto it = m.find(1);
    m.erase(it);//用迭代器删除
    int s = m.erase(1);//用关键字删除,删除了会返回1
    m.erase(m.begin(),m.end());//删除整个map
    return 0;

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值