map::emplace with muliple constructor arguments

4,336 views
Skip to first unread message

Florian Lindner

unread,
May 2, 2016, 8:46:16 AM5/2/16
to std-dis...@isocpp.org
Hello,

I have this piece of code:

#include <map>
#include <tuple>

class Test {
public:
Test(int a, int b) : _a(a), _b(b) {}

int _a, _b;
};


int main(int argc, char *argv[])
{
std::map<int, Test> map;

map.emplace(0, 1, 2);
return 0;
}


I try to insert a Test object that is initialized with a=1, b=2. The
std::map key should be 0.

However, this does not work like that. I also tried putting 1,2 insert
a make_tuple.

Thanks,
Florian

Robert Jakob

unread,
May 2, 2016, 9:47:27 AM5/2/16
to std-dis...@isocpp.org
There are several examples here:
http://en.cppreference.com/w/cpp/container/map/emplace

As far as I can see, it isn't possible to do this with
one call and direct ctor argument to m.emplace only.

In your example:

map.emplace(std::piecewise_construct,
std::forward_as_tuple(0),
std::forward_as_tuple(1,2));

Best,
r.

Ville Voutilainen

unread,
May 2, 2016, 10:12:47 AM5/2/16
to std-dis...@isocpp.org
Why not just write

map.emplace(0, Test(1, 2));

?
Message has been deleted

codyd...@gmail.com

unread,
Jan 24, 2019, 8:47:24 AM1/24/19
to ISO C++ Standard - Discussion
Extending from this Stack Overflow post, if you write "map.emplace(0, Test(1,2))", I believe it will create a temporary object of type Test given parameters (1,2), then copy the Test object into the map, then destruct the temporary Test object. The purpose of the emplace function is to be able to construct your objects in the correct place initially, so no copying and/or destruction has to occur.

tko...@google.com

unread,
Jan 25, 2019, 11:29:53 AM1/25/19
to ISO C++ Standard - Discussion, mailin...@xgm.de
On Monday, 2 May 2016 13:46:16 UTC+1, Florian Lindner wrote:
Hello,

I have this piece of code:

#include <map>
#include <tuple>

class Test {
public:
  Test(int a, int b) : _a(a), _b(b) {}

  int _a, _b;
};


int main(int argc, char *argv[])
{
  std::map<int, Test> map;

  map.emplace(0, 1, 2);
  return 0;
}


I try to insert a Test object that is initialized with a=1, b=2. The
std::map key should be 0.

How about "map.try_emplace(0, 1, 2);"?

Reply all
Reply to author
Forward
0 new messages