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;
}