You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++中嵌套vector的两类map容器如何emplace插入及访问元素

std::map完全支持存储vector类型数据,两个问题的具体解答如下:

问题1:向map<string, vector<int>>容器emplace数据

手动构造插入

直接在emplace参数中构造key和对应的vector即可,示例:

// 插入题目给出的三行输入
mp.emplace("ONE", std::vector<int>{1, 11, 111, 1111});
mp.emplace("TWO", std::vector<int>{22, 2, 2222});
mp.emplace("THREE", std::vector<int>{333, 3333, 3});

从输入流自动读取插入

如果是逐行读取输入批量插入,可以用字符串流拆分每行内容,示例代码:

#include <map>
#include <vector>
#include <string>
#include <sstream>
#include <iostream>

int main() {
    std::map<std::string, std::vector<int>> mp;
    std::string line;
    // 逐行读取输入
    while (std::getline(std::cin, line)) {
        std::istringstream iss(line);
        std::string key;
        iss >> key;
        std::vector<int> vals;
        int num;
        while (iss >> num) {
            vals.push_back(num);
        }
        // 移动语义减少拷贝开销
        mp.emplace(std::move(key), std::move(vals));
    }
    return 0;
}
问题2:map<vector<int>, vector<int>>的使用说明

可行性说明

可以正常实现。std::vector默认重载了operator<,符合std::map对key类型必须支持小于比较的要求,排序规则为vector元素的字典序比较。

emplace插入元素

操作和普通map一致,直接传入两个vector参数即可:

std::map<std::vector<int>, std::vector<int>> mp;
// 插入示例
mp.emplace(std::vector<int>{1,2,3}, std::vector<int>{4,5,6});

元素访问

有两种常用访问方式:

  • 下标访问:注意如果key不存在,会自动插入默认构造的空vector作为value
// 读取key为{1,2,3}对应的value
std::vector<int> val = mp[{1,2,3}];
  • find查找访问:不会触发默认插入,更安全
auto iter = mp.find(std::vector<int>{1,2,3});
if (iter != mp.end()) {
    // iter->first 为key(vector<int>类型)
    // iter->second 为对应的value(vector<int>类型)
    for (int num : iter->second) {
        std::cout << num << " ";
    }
}

注意:vector作为key时,单次比较的时间复杂度为O(n)(n为vector长度),数据量较大时性能会低于基础类型key,可根据业务场景选择使用。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 16:24:03