map嵌套map容器
定义一个map嵌套map的容器
map<string,map<string,int> >m;
给m容器进行初始化
m["s1"]["t1"]=5;
m["s2"]["t2"]=7;
输出代码:
for(map<string,map<string,int>>::iterator it1=m.begin();it1!=m.end();it1++)
{
cout<<it1->first<<endl;
for(map<string,int>::iterator it2=it1->second.begin();it2!=it1->second.end();it2++)
{
cout<<it2->first<<it2->second<<endl;
}
}
输出:
s1
t1 5
t2 7
说明map容器中value的map也是一个容器 可以放很多数据类型为map的数据
迭代器和基于范围for循环的区别
迭代器
上面在进行map嵌套map容器的输出的时候用的是两个迭代器 直接定义了迭代器的类型
迭代器是直接指向容器元素的指针或类似指针的对象
std::map<int, int> m;
for (std::map<int, int>::iterator it = m.begin(); it != m.end(); ++it) {
std::cout << it->first << ": " << it->second << std::endl;
}
这里,it 是一个迭代器对象,类型为 std::map<int, int>::iterator,它指向 std::pair<const int, int> 类型的元素。迭代器的设计使其能够正确解引用为 std::pair<const int, int>,因此没有类型不匹配的问题。
基于范围for循环
基于范围的for循环直接处理容器的元素,而不是迭代器。因此,迭代变量的类型必须与容器圆度的类型匹配:
std::map<int, int> m;
for (const auto& element : m) {
std::cout << element.first << ": " << element.second << std::endl;
}
在这种情况下,element 是 std::pair<const int, int> 类型的对象,而不是 std::map<int, int>。
题外话
在使用迭代器查找map容器中的元素的时候使用的是“->”,在使用基于范围的for循环的时候的用的是“.”。
当使用迭代器时,迭代器是一个类似于指针的对象,它指向容器中的元素。为了访问迭代器指向的元素,我们使用箭头操作符(->)或解引用操作符(*)。
当使用解引用的操作符的时候也是用“.”。
std::map<int, int> m = {{1, 2}, {3, 4}, {5, 6}};
for (std::map<int, int>::iterator it = m.begin(); it != m.end(); ++it) {
// 使用箭头操作符访问键和值
std::cout << it->first << ": " << it->second << std::endl;
// 或者使用解引用操作符
// std::cout << (*it).first << ": " << (*it).second << std::endl;
}
在基于范围的 for 循环中,循环变量直接是容器的元素,不需要通过迭代器来间接访问。因此,我们直接使用点操作符(.)来访问元素的成员。
std::map<int, int> m = {{1, 2}, {3, 4}, {5, 6}};
for (const auto& element : m) {
// 使用点操作符访问键和值
std::cout << element.first << ": " << element.second << std::endl;
}
迭代器:指向容器中的元素,通过箭头操作符(->)或解引用操作符(*)来访问元素。
基于范围的 for 循环:循环变量直接是容器的元素,通过点操作符(.)来访问元素的成员。
这解释了为什么在使用迭代器时需要用箭头操作符,而在基于范围的 for 循环中则使用点操作符。