Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

map::emplace() with a custom value type

Tags:

I'm having trouble using map::emplace(). Can anyone help me figure out the right syntax to use? I am effectively trying to do the same thing as in this example. Here is my version:

#include <map>
using namespace std;

class Foo
{
  // private members

  public:
    Foo(int, char, char) /* :init(), members() */ {  }

    // no default ctor, copy ctor, move ctor, or assignment
    Foo() = delete;
    Foo(const Foo&) = delete;
    Foo(Foo &&) = delete;
    Foo & operator=(const Foo &) = delete;
    Foo & operator=(Foo &&) = delete;
};


int main()
{
  map<int, Foo> mymap;
  mymap.emplace(5, 5, 'a', 'b');

  return 0;
}

Under GCC 4.7 (with the -std=c++11 flag), I am erroring out on the emplace line. The example I linked above doesn't say anything about how to deal with custom types instead of primitives.

like image 535
Nicu Stiurca Avatar asked Dec 28 '12 20:12

Nicu Stiurca


People also ask

What is MAP emplace?

map emplace() in C++ STL The map::emplace() is a built-in function in C++ STL which inserts the key and its element in the map container.

Is map ordered c++?

By default, a Map in C++ is sorted in increasing order based on its key.

How is ordered map implemented in c++?

std::map is a sorted associative container that contains key-value pairs with unique keys. Keys are sorted by using the comparison function Compare . Search, removal, and insertion operations have logarithmic complexity. Maps are usually implemented as red-black trees.


1 Answers

A container's emplace member constructs an element using the supplied arguments.

The value_type of your map is std::pair<const int, Foo> and that type has no constructor taking the arguments { 5, 5, 'a', 'b' } i.e. this wouldn't work:

std::pair<const int, Foo> value{ 5, 5, 'a', 'b' };
map.emplace(value);

You need to call emplace with arguments that match one of pair's constructors.

With a conforming C++11 implementation you can use:

mymap.emplace(std::piecewise_construct, std::make_tuple(5), std::make_tuple(5, 'a', 'b'));

but GCC 4.7 doesn't support that syntax either (GCC 4.8 will when it's released.)

like image 130
Jonathan Wakely Avatar answered Oct 22 '22 16:10

Jonathan Wakely