You need to enable JavaScript to run this app. C++中如何向multimap插入Title、Genre、Rating三项并遍历输出?
优惠活动
大模型
产品
解决方案
定价
更多

C++中如何向multimap插入Title、Genre、Rating三项并遍历输出?

multimap多字段存储的正确实现与常见错误修正

核心错误说明

  • 模板参数使用错误:std::multimap的固定模板参数顺序为键类型、映射值类型、键比较器类型,第三个参数默认用std::less<键类型>实现按键排序的逻辑,根本不支持直接传入第三个存储字段的类型。你代码里写的multimap<string, string, int> hi,相当于把int类型当成了排序比较器,完全不符合语法要求,连编译都过不了。
  • pair类型误用:std::pair是固定的二元键值对结构,不存在带三个模板参数的版本,代码里pair<string, string, int>的写法没有任何标准实现对应。

可行的插入实现方法

multimap本质是「键 -> 关联值」的映射结构,关联值可以是任意自定义复合类型,你只要把非键的两个字段打包成自定义结构,作为multimap的关联值类型,就能实现三字段的存储。

  1. 首先定义一个简单的结构,用来存Genre和Rating两个字段:
struct MovieInfo {
    string genre;
    int rating;
};
  1. 定义multimap实例时,把Title设为键类型,MovieInfo设为关联值类型:
multimap<string, MovieInfo> hi;
  1. 插入时构造完整的键值对即可:
hi.insert(make_pair(title, MovieInfo{gerne, rating}));

原代码的逻辑漏洞:你现在是读完Title、Genre、Rating三个字段之后,才判断输入的Title是不是终止符".",这会导致代表终止符的无效条目被插入到multimap里才触发break。调整下逻辑,读完Title就先判断是不是终止符,如果是直接跳出循环,不用继续读后续字段。

遍历打印方法

multimap的迭代器指向的每个元素都是const 键类型, 关联值类型的二元结构,遍历时直接拆解取值就行,示例:

for (const auto& entry : hi) {
    cout << "Title: " << entry.first 
         << " | Genre: " << entry.second.genre 
         << " | Rating: " << entry.second.rating 
         << endl;
}

修正后可直接运行的完整代码

#include<iostream>
#include<string>
#include<map>
using namespace std;

struct MovieInfo {
    string genre;
    int rating;
};

int main() {
    multimap<string, MovieInfo> hi;
    string title, gerne;
    int rating; 

    cout << "Please enter a title, genre and rating, exit by entering '.' as title" << endl;
    while (true) {
        cout << "Title:";
        cin >> title;
        // 提前判断终止条件,避免无效数据插入
        if (title == ".") break;

        cout << endl << "Genre:";
        cin >> gerne;

        cout << endl << "Rating:"; 
        cin >> rating;

        hi.insert(make_pair(title, MovieInfo{gerne, rating}));
    }
    // 遍历打印所有存储的条目
    cout << "\nStored entries:" << endl;
    for (const auto& entry : hi) {
        cout << "Title: " << entry.first 
             << " | Genre: " << entry.second.genre 
             << " | Rating: " << entry.second.rating 
             << endl;
    }
    return 0; 
}

内容的提问来源于stack exchange,提问作者user15048696

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.28 12:15:04