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

如何将一个std::map的键复制到另一个std::map中?

解决std::map仅复制键的问题

原代码的问题

  1. ptr初始为空,it2 = ptr.cbegin()指向容器末尾的空位置,直接访问it2->first会触发未定义行为。
  2. std::map的键是不可修改的(first成员为const类型),无法直接赋值修改。
  3. cbegin()返回的是常量迭代器,本身也不允许修改容器元素。

正确实现方式

方法1:范围for循环(最直观)

遍历原map的每个键值对,将键插入新map,值先初始化为nullptr(后续可修改):

#include <iostream>
#include <map>

int main() {
  
  std::map<std::string, int> size = {
    {"a", 1},
    {"b", 2},
    {"c", 3}
  };

  std::map<std::string, void*> ptr;
  // 遍历原map,插入键并初始化值为nullptr
  for (const auto& item : size) {
    ptr[item.first] = nullptr;
  }

  // 后续为ptr赋值示例
  ptr["a"] = reinterpret_cast<void*>(0x123);
  ptr["b"] = reinterpret_cast<void*>(0x456);

  // 验证结果
  for (const auto& item : ptr) {
    std::cout << item.first << ": " << item.second << std::endl;
  }

  return 0;
}

方法2:使用std::transform算法

借助标准库算法完成转换,需要包含<algorithm>和<iterator>头文件:

#include <iostream>
#include <map>
#include <algorithm>
#include <iterator>

int main() {
  
  std::map<std::string, int> size = {
    {"a", 1},
    {"b", 2},
    {"c", 3}
  };

  std::map<std::string, void*> ptr;
  // 转换原map的键为新map的键值对
  std::transform(size.cbegin(), size.cend(),
                 std::inserter(ptr, ptr.end()),
                 [](const std::pair<const std::string, int>& item) {
                   return std::make_pair(item.first, static_cast<void*>(nullptr));
                 });

  // 后续赋值示例
  ptr["c"] = reinterpret_cast<void*>(0x789);

  // 验证结果
  for (const auto& item : ptr) {
    std::cout << item.first << ": " << item.second << std::endl;
  }

  return 0;
}

方法3:传统迭代器循环

如果习惯使用迭代器遍历,可采用以下方式:

#include <iostream>
#include <map>

int main() {
  
  std::map<std::string, int> size = {
    {"a", 1},
    {"b", 2},
    {"c", 3}
  };

  std::map<std::string, void*> ptr;
  auto it = size.cbegin();
  while (it != size.cend()) {
    // 插入键值对,值初始化为nullptr
    ptr.insert(std::make_pair(it->first, nullptr));
    ++it;
  }

  // 后续操作...

  return 0;
}

补充说明

  • ptr[key] = value:若键不存在则插入新元素,若已存在则覆盖值,适合本次场景的初始化需求。
  • insert方法:若键已存在则不会修改现有值,返回的pair可判断插入是否成功,适合需要避免覆盖的场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 00:45:25