int main()
{
multimap<string, string> m{
{"yiyi","nihao"},
{"gcl","hello"},
{"gcl","world"}
};
map<string, multiset<string>> order_m;//1.why order_m can't be multimap
for (const auto author : m)
order_m[author.first].insert(author.second);
for (const auto author : order_m)
{
cout << author.first << " : ";
for (const auto work : author.second)//2.why i can't use order_m.second
cout << work << " "<<endl;
}
system("pause");
return 0;
}
这段代码定义一个作者及其作品的multimap,并使它按字典序打印作者列表和他们的作品。功能的确实现了,但是有两个问题(在代码中有标注)。
1.为什么使用multimap定义order_m 的时候 下一行for循环遍历的时候不能使用下标运算符,显示无法匹配相应元素。
2.为什么在for循环遍历中可以使用author.second,却不能使用order_m.second,编译器会提示order_m并没有元素second,可是author不是只是order_m的别名而已吗?
1、multimap是关联容器,不能通过for(i = 1, i< size; ++i)方式访问元素,那是顺序容器才支持的功能。
2、order_m是容器,是一个map,它类似{[key]=value, ...},他没有second元素
author不是order_m的别名,他是在遍历order_m过程中的迭代器,for每运行一次,author就变成order_m
的下一个元素。只有迭代器才有first和second两个结构可以访问。
希望可以帮到你。
multimap如果是multimap,那么下标运算符就不知道是哪个对象,因为可能有多个。