C++ Map常见用法说明

map简介

C++中map提供的是一种键值对容器,里面的数据都是成对出现的,如下图:每一对中的第一个值称之为关键字(key),每个关键字只能在map中出现一次;第二个称之为该关键字的对应值。
这里写图片描述

map中常用的方法

clear() 删除所有元素
insert() 插入元素
size() 返回map中元素的个数

#include<iostream>
#include<map>
using namespace std;
int main()
{
    std::map<int,int> m;
    for(int i=0; i<10; i++)
    {
        m[i]=i;//写题时,通常这样插入
    }
    m.insert(std::pair<int, int>(10, 100));//没这样插入过
    for(int i=0; i<=10; i++)
        cout<<m[i]<<" ";
    cout<<endl;
    int sum=m.size();
    cout<<"map内元素的数量为sum="<<m.size()<<endl;
    m.clear();//清空
    sum=m.size();
    cout<<"清空后sum="<<sum<<endl;
    return 0;
}

begin() 返回指向map头部的迭代器
end() 返回指向map末尾的迭代器
find(x) 返回查找一个元素的迭代器下(x为下标)
count() 返回指定元素出现的次数(非0即1,你懂的)
empty() 如果map为空则返回true
erase(x) 删除一个元素(x为下标)
lower_bound(x) 返回键值>=给定元素的第一个位置(x为下标)
upper_bound(x) 返回键值>给定元素的第一个位置(x为下标)
swap() 交换两个map

#include<iostream>
#include<map>
using namespace std;
int main()
{
    std::map<int,int> m;
    std::map<int,int> mp;
    for(int i=0; i<10; i++)
    {
        m[i]=i+1;//写题时,通常这样插入
    }
    m[10]=1;

    map<int,int>::iterator t1=m.begin();
    for(; t1!=m.end(); ++t1)
        cout<< t1->first <<"==>"<< t1->second <<endl;

    cout<<"1是否出现"<<m.count(1)<<endl;

    if(!m.empty())
        cout<<"map中不为空"<<endl;

    cout<<"下标为5的元素为="<<m.find(5)->second<<endl;

    m.erase(5);
    cout<<"删除下标为5的元素后"<<endl;
    for(t1=m.begin(); t1!=m.end(); ++t1)
        cout<< t1->first <<"==>"<< t1->second <<endl;

    cout<<"大于等于(下标6)的第一个元素的位置和数 "<<m.lower_bound(6)->first<<"==>"<<m.lower_bound(6)->second<<endl;
    cout<<"大于(下标6)的第一个元素的位置和数 "<<m.upper_bound(6)->first<<"==>"<<m.upper_bound(6)->second<<endl;

    mp[0]=1000;
    m.swap(mp);
    cout<<"m数组元素为"<<endl;
    map<int,int>::iterator it;
    for(it=m.begin();it!=m.end();it++)
        cout<<it->first<<"==>"<<it->second<<endl;
    cout<<"mp数组元素为"<<endl;
    for(it=mp.begin();it!=mp.end();it++)
            cout<<it->first<<"==>"<<it->second<<endl;
    return 0;
}

转载:http://blog.csdn.net/zxy160/article/details/76461724

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值