C++ 如何使用转发参数在 std::map 中使用 emplace

问题描述 投票:0回答:1

通过

std::vector
,我成功地通过转发参数来使用
emplace_back
,如以下代码所示:

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

using namespace std;

struct Complicated
{
  int i;
  double d;
  string s;

 Complicated(int a, double b, std::string c): i{a}, d{b}, s{c}{};
};

int main()
{
  std::vector<Complicated> m;
  int anInt = 4;
  double aDouble = 5.0;
  std::string aString = "C++";

  m.emplace_back(anInt,aDouble,aString);
  return 0;
}

地图也应该发生类似的事情:

  std::map<int, Complicated> m;
  int anInt = 4;
  double aDouble = 5.0;
  std::string aString = "C++";

  m.emplace(4,anInt,aDouble,aString);

但我收到以下错误:

emplace_back.cpp:28:39:   required from here
/usr/include/c++/9/ext/new_allocator.h:146:4: error: no matching function for call to ‘std::pair<const int, Complicated>::pair(int, int&, double&, std::__cxx11::basic_string<char>&)’
  146 |  { ::new((void *)__p) _Up(std::forward<_Args>(__args)...); }
  |    ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

我怎样才能做到这一点?

c++ dictionary emplace
1个回答
0
投票

对于此场景,您可以使用

std::pair
构造函数并采用
std::piecewise_construct_t

m.emplace(std::piecewise_construct,
          std::forward_as_tuple(4),
          std::forward_as_tuple(anInt, aDouble, aString));
© www.soinside.com 2019 - 2024. All rights reserved.