c++stl中的map/multimap

1. 初始化,例如:map<string,float,less<int> > m;

也可以为map<string,float>这时的第三个参数省略了,则默认为是less<int>,这个表示为默认升序,而greater<int>默认为降序。

2. 插入元素,按照键值从小到大存入,例如:

map<string,float> m;

m[Jack]=90;

m[Make]= 80;

定义迭代器:map<string,float>::iterator  it;

输出的形式:

for(it=m.begin();it!=m.end();it++)

cout<<(*it).first<< : <<(*it).second<<endl;

3. 删除:用erase()函数,例如:m.erase(Jack);

4. 清除:用clear()函数,例如:m.clear();

5. 大小:  size()函数, 例如:m.size();

6. 反向迭代,用reverse_iterator  rit;  for(rit=m.rbegin();rit!=m.rend();rit++)

7. find()按键值查找, 是按键值查找的,返回一个被查找的元素的迭代器,若没有找到则返回,end()的迭代器。例如:

map<int,char> m;

m[25]=m;

map<int,char>::iterator it;

It=m.find(25);

If(it!=m.end())

cout<<(*it).first<< : <<(*it).second<<endl;

Else

cout<<not find<<endl;

8. 自定义比较函数,重载()”运算符,代码如下:

#include<iostream>

#include<string>

#include<map>

using namespace std;

struct myComp

{

bool operator()(const int &a,const int &b)

{

if(a!=b)

return a>b;

else

return a>b;

}

};

int main()

{

map<int,char,myComp> m;

m[25]='m';

m[28]='k';

m[10]='x';

m[30]='a';

map<int,char,myComp>::iterator it;

for(it=m.begin();it!=m.end();it++)

cout<<(*it).first<<" : "<<(*it).second<<endl;

return 0;

}

9. map实现数字字符串的分离,代码如下:

#include<iostream>

#include<string>

#include<map>

using namespace std;

int main()

{

map<char,int> m;

for(int j=0;j<10;j++)

m['0'+j]=j;

string sa;

sa="6234";

int i,sum=0;

for(i=0;i<sa.length();i++)

sum+=m[sa[i]];

cout<<"sum = "<<sum<<endl;

return 0;

}

10. 自定义排序规则,代码如下:

#include<iostream>

#include<string>

#include<map>

using namespace std;

struct Info{

string name;

float score;

bool operator < (const Info &a) const  //重载"<"操作符,自定义排序规则

{

return a.score<score; //score由大到小排列,如果要由小到大排列,使用">"号即可

}

};

int main()

{

map<Info,int> m;

Info info;

info.name="Jack";

info.score=60;

m[info]=25;

info.name="Bomi";

info.score=80;

m[info]=10;

info.name="Peti";

info.score=66.5;

m[info]=30;

map<Info,int>::iterator it;

for(it=m.begin();it!=m.end();it++)

{

cout<<(*it).second<<" : ";

cout<<((*it).first).name<<" "<<((*it).first).score<<endl;

}

return 0;

}

Multimap

1. multimapmap基本相同,但是插入元素用insert()方法,且multimap可以存入重复的键值例如:

multimap<String,double>  m;

m.insert(pair<string,double>("Jack",300.5));

m.insert(pair<string,double>("Kity",200));

m.insert(pair<string,double>("Memi",500));

m.insert(pair<string,double>("Jack",306));

如果定义为map的,若重复插入Jack则,新插入的替代原来插入的。

2. erase()函数用来删除,例如:

m.erase(Jack);就把所有键值为Jack的元素删除。

3. find()函数用来查找,若找到则返回值一个被查找的元素的迭代器,若没有找到则返回m.end()

若有重复的键值,则返回第一个键值的迭代器。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值