c++ - 在 std::map 中,如何编写分配器来接受键作为值的构造函数参数?

标签 c++

例如:

#include <map>
class A {
 public:
  A(int i) {}
};

std::map<int, A> as;

int main() {
  A& a = as[1];
}
此代码将导致无法编译,因为 A没有默认构造函数。
那么如何(或者我可以?)编写一个分配器,它将创建一个 A通过使用 1作为构造函数参数?

最佳答案

您可以为 try_emplace 添加一个包装器试图安置一个新的A给定键的元素(如果它不存在),使用键的值作为 try_emplace转发论据。您可以在 if 中的初始化语句中组合结构化绑定(bind)。语句可以巧妙地获取新插入的元素或访问预先存在的元素。

#include <iostream>
#include <map>
#include <utility>

struct A {
  A(int i) : i_(i) {}
  int i_;
};

template <typename Key>
auto try_emplace_key_as_arg(std::map<Key, A> &m, Key &&key) {
  return m.try_emplace(key, std::forward<Key>(key));
}

template <typename Key>
void try_emplace_with_diagnostics(std::map<Key, A> &m, Key &&key) {
  if (auto [it, was_inserted] =
          try_emplace_key_as_arg(m, std::forward<Key>(key));
      was_inserted) {
    std::cout << "\nNew: " << it->second.i_;
  } else {
    std::cout << "\nAlready existed: " << it->second.i_;
  }
}

int main() {
  std::map<int, A> as{{2, A{2}}};
  try_emplace_with_diagnostics(as, 1); // New: 1
  try_emplace_with_diagnostics(as, 2); // Already existed: 2
}

关于c++ - 在 std::map 中,如何编写分配器来接受键作为值的构造函数参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63575915/

相关文章:

c++ - 使用 C++ 预处理器从单独的组件构造版本字符串

c++ - C++ 中 vector 的内部工作?

c++ - g++5 中 std::unordered_set 的不完整类型编译错误,在 clang++ 中编译

c++ - 从 WINAPI 获取文件的先前版本

如果 Printf 在函数中,则 C++ Return 不同

c++ - 如何增加 QNetworkReply::downloadProgress 信号频率?

c++ - Eigen SparseLU 分解问题

c++ - 如何在 vector 中找到第一个重复项 - C++?

c++ - 处理系统调用\标准库异常故障

c++ - 将空基类指针转换为子类指针?