map容器
-
**<键,值>**对
-
键值不允许重复。
-
如果map中没有键值,而直接插入,则操作是允许的;另外如果直接使用“++”运算符,则从0开始直接计数。并把这个<键,值>对插入到map中。
常用函数和操作
1.map的创建、插入和遍历
#include<map>
#include<iostream>
#include<string>
using namespace std;
int main()
{
map<string, float> a;
a["hehe"] = 12.5;
a["xixi"] = 89.6;
map<string, float>::iterator it;
for(it = a.begin(); it != a.end(); it++)
cout<<(*it).first<<' '<<(*it).second<<endl;
a["hehe"] = 45.2;
cout<<"修改后的hehe的值:"<<a["hehe"]<<endl;
}
(*it).first 表示键,注意键不可以用这种方法修改,如:
(*it).first = "eee",是错误的操作。
(*it).second 表示对应的值
2.查找键和删除键
可以使用clear()清空map
map<int, int> a;
a.clear();
也可以使用erase()删除。括号中可以直接写相应的键值,也可以写iterator的位置。
a.erase("hehe");//直接使用键,删除“hehe”;
a.erase(++a.begin());//删除“xixi”
使用**find()**函数可以搜索某个键。搜索到了的话返回迭代器的位置,搜索不到返回end()位置。
#include<map>
#include<iostream>
#include<string>
using namespace std;
int main()
{
map<string, float> a;
a["hehe"] = 12.5;
a["xixi"] = 89.6;
map<string, float>::iterator it;
it = a.find("xixi");
a.erase(it);
for(it = a.begin(); it != a.end(); it++)
cout<<(*it).first<<' '<<(*it).second<<endl;
}
另外,把元素插入到map中时,自动按照键值从小到大排序。可以自己设置比较函数,比较函数的写法类似于sort()中的写法。
//未使用自定义比较函数时
#include<iostream>
#include<map>
using namespace std;
bool comp(int a, int b){
}
int main()
{
map<int, char> a;
a[10] = 'a';
a[5] = 'b';
a[25] = 'c';
a[15] = 'd';
map<int, char>::iterator it;
for(it = a.begin(); it != a.end(); it++)
cout<<(*it).first<<' '<<(*it).second<<endl;
}
#include<iostream>
#include<map>
using namespace std;
struct mycomp
{
bool operator() (const int &a, const int &b)
return a > b;
};
int main()
{
map<int, char, mycomp> a;
a[10] = 'a';
a[5] = 'b';
a[25] = 'c';
a[15] = 'd';
map<int, char, mycomp>::iterator it;
for(it = a.begin(); it != a.end(); it++)
cout<<(*it).first<<' '<<(*it).second<<endl;
}
对于结构体,需要重载。。