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

如何访问const map的键和值?合并map时const容器无法操作是什么问题

问题原因
  • const map<int, int>& container2的const修饰代表这个传入的map是只读不可修改的,你代码中container2.erase(it2)属于修改容器的操作,const对象无法调用erase这类非const成员函数,编译阶段就会直接报错。
  • 哪怕你去掉const,当前代码也存在严重bug:调用erase(it2)之后it2迭代器会直接失效,后续执行it2++属于未定义行为,大概率会触发程序崩溃。
  • 额外的逻辑问题:两层循环遍历两个有序map的时间复杂度是O(n*m),效率极低,完全没有必要。
修正方案

你想要的效果是把container2中不存在于container1的键值对插入到container1里,不需要修改container2本身,直接遍历判断即可,正确代码如下:

void mergeContainers(map<int, int>& container1, const map<int, int>& container2)
{
    // 直接遍历container2,判断键是否在container1中不存在,不存在就插入
    for (const auto& pair : container2) {
        if (container1.find(pair.first) == container1.end()) {
            container1.insert(pair);
        }
    }
}

如果你的C版本支持C17,还可以用更简洁的std::map::merge接口直接实现需求,不需要自己写循环:

void mergeContainers(map<int, int>& container1, const map<int, int>& container2)
{
    auto temp = container2;
    container1.merge(temp);
}

注意merge接口会拿走源容器里的元素,如果不想修改源容器就像上面一样拷贝一份临时变量即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 19:36:01