map
map 也是一种集合,它同样可以包含多个元素,每一个元素由一个键值和一个与键值相关联的值组合而成,这样的元素又称键值对(<key, value>)。
example
#include <iostream>
#include <map>
using namespace std;
int main()
{
map<char, int> m;
m['a'] = 1;
m['b'] = 2;
m['c'] = 3;
m['d'] = 4;
m['a'] = 5;
map<char, int>::iterator itor;
for(itor = m.begin(); itor != m.end(); itor++)
{
cout << "<" << itor->first <<"> - <" << itor->second << ">"<< endl;
}
return 0;
}

本例是一个 map 容器的示例程序,我们直接看主函数。主函数一开始定义了一个 map 容器实例 m,map<char, int>m;语句中 char 表示键的数据类型,int 表示与键值对应的值的数据类型。
我们用字符来作为键,键在 map 中是不允许出现重复的,但是与键对应的值 value 可以重复,例如 m[‘a’] 和 m[‘e’] 相同。但是如果键值出现相同,则以最后一次出现的作为结果,例如本例中一开始“m[‘a’] = 1;”,在后面又出现“m[‘a’] = 0;”,此时不会有语法错误,这两句可以理解为“m[‘a’] = 1;”是给“m[‘a’]”赋初值,而“m[‘a’] = 0;”则可以理解为将“m[‘a’]”的值修改为 0。
遍历 map 时同样是使用迭代器,在函数中我们定义了一个 itor 迭代器,由于 map 中是由元素对组成的,包含两个元素,因此遍历方法与前面所介绍的容器稍有不同,前面的容器用 *itor 就可以直接获得所需要的元素,而 map 容器则需要通过 itor->first 访问键值,并用 itor->second 访问与键值对应的值。
注意
map 容器则需要通过 itor->first 访问键值,并用 itor->second 访问与键值对应的值。
map<char, int>::iterator itor;
for(itor = m.begin(); itor != m.end(); itor++)
{
cout << "<" << itor->first <<"> - <" << itor->second << ">"<< endl;
}
insert
#include <iostream>
#include <map>
using namespace std;
int print(map<int, int> m)
{
map<int, int>::iterator itor;
for(itor = m.begin(); itor != m.end(); itor++)
{
cout << "<" << itor->first <<"> - <" << itor->second << ">"<< endl;
}
return 0;
}
int main()
{
map<int, int> maps;
maps.insert(pair<int, int> (10, 15));
print(maps);
map<int, int> maps1;
maps1.insert(make_pair(11, 16));
print(maps1);
map<int, int> maps2;
typedef pair<int, int> Int_Pair;
maps2.insert(Int_Pair(12, 17));
print(maps2);
return 0;
}
小结
map 是经典的键值关联容器
本文介绍了C++标准库中的关联式容器map,包括如何使用map存储键值对,以及如何通过迭代器遍历并访问键值。示例程序展示了如何初始化、插入元素以及遍历map。在map中,键是唯一的,而值可以重复。当键重复时,以最后一次插入的值为准。插入元素的方法包括使用`insert`函数,可以通过`pair`、`make_pair`或直接指定键值对进行插入。
363

被折叠的 条评论
为什么被折叠?



