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 kali环境运行volatility分析android内存文件,缺profile
  • ¥15 写uniapp时遇到的问题
  • ¥15 vs 2008 安装遇到问题
  • ¥15 matlab有限元法求解梁带有若干弹簧质量系统的固有频率
  • ¥15 找一个网络防御专家,外包的
  • ¥100 能不能让两张不同的图片md5值一样,(有尝)
  • ¥15 informer代码训练自己的数据集,改参数怎么改
  • ¥15 请看一下,学校实验要求,我需要具体代码
  • ¥50 pc微信3.6.0.18不能登陆 有偿解决问题
  • ¥20 MATLAB绘制两隐函数曲面的交线