概述
map是STL的一个关联容器,它提供一对一的数据处理能力。(其中第一个可以称为关键字,
每个关键字只能在map中出现一次,第二个可以称为该关键字的值)
比方说 字典, 统计单词
下面就通过简单易懂的代码对其讲解
#include <iostream>
#include <map>
using namespace std;
//构造方法 int char float double string 甚至结构体 都可以任意搭配
map <string, int> month;
map <int, char> m;
struct node //结构体类型
{
string name;
float score;
//从小到大
bool operator < (const node &a) const
{
return a.score > score;
}
};
int main()
{
// 赋值方式
month["January"] = 1;
month["February"] = 2;
month["July"] = 7;
// 迭代器
map <string, int>::iterator
it;
for(it = month.begin(); it != month.end(); ++ it)
{
//两种方式
cout << it -> first << " " << it -> second << endl;
cout << (*it).first << " " << (*it).second << endl;
}
///map 的大小
int l = month.size();
cout << "map 的数据个数:" << l << endl;
/// find 查找键值 返回位置
m[25] = 'm';
m[47] = 's';
map <int, char>::iterator t = m.find(25);//查找键值, 返回位置。
if(t != m.end())
{
cout << (*t).first << ":" << (*t).second << endl;
}
else
{
cout << "not find !" << endl;
}
/// 结构体形式 可实现排序功能
map<node, int> m1;
node n;
n.name = "Jack";
n.score = 87.6;
m1[n] = 45;
n.name = "Tom";
n.score = 90.0;
m1[n] = 46;
n.name = "Timi";
n.score = 66.6;
m1[n] = 47;
for(map<node, int> :: iterator it1 = m1.begin(); it1 != m1.end(); ++ it1)
{
cout << (*it1).second << endl;
cout << ((*it1).first).name << " " << ((*it1).first).score << endl;
}
return 0;
}
最后
以上就是和谐小蘑菇为你收集整理的STL_映射_【map】的全部内容,希望文章能够帮你解决STL_映射_【map】所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复