c++ - 返回包含 std::map 的 std::unique_ptr

标签 c++ stdmap unique-ptr

我有一张 map 的 map 如下:

std::map<char,std::map<short,char>> my_maps;

并且我需要从一个函数中返回对与指定键对应的映射之一的引用。 我不知道该怎么做,这是我的代码:

bool GetMap(char key,std::unique_ptr<std::map<short,char>> my_map){


  auto m=my_maps.find(key);
  if(m!=my_maps.end()){

     my_map=m->second;
     // I have also tried this: my_map=my_maps[_commandcode];

    return(true);
  }
  return (false);
}

最佳答案

这就是我要做的:

std::map<short,char>& GetMap(char key, std::map<char,std::map<short,char>> &my_maps)
{
  auto m = my_maps.find(key);
  if (m != my_maps.end())
  {
    return m->second;
  }
  throw std::exception("not found");
}

关于c++ - 返回包含 std::map 的 std::unique_ptr,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14208968/

相关文章:

c++ - boost 定时器 24 小时格式

c++ - 使用 g++ 静态链接到 libcrypto++

c++ - 模板解析因 boost multiprecision + Eigen 而失败

c++ - 可扩展条件语句的机制

c++ - 我可以扩展 std::map::lower_bound 以搜索非 key_type 参数吗?

c++ - 为什么 unique_ptr 会重载 reset(pointer p = pointer()) 和 reset(nullptr_t)?

c++ - 成员函数的“this”参数的类型为 'const' ,但我的函数实际上不是 'const'

C++ 在 std::map 中存储对值的引用

c++ - 为什么我的 unique_ptr 认为它有一个空函数指针删除器?

c++ - 使用shared_ptr而不是unique_ptr作为类成员只是为了避免隐式复制构造函数删除是否明智?