G____yiyi 2015-06-14 08:39 采纳率: 62.5%
浏览 2124
已采纳

关于for()循环和map(multimap)的问题

 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的别名而已吗?

  • 写回答

2条回答 默认 最新

  • 帘卷西风 博客专家认证 2015-06-14 14:19
    关注

    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两个结构可以访问。

    希望可以帮到你。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog