Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing references in a map

I tried to store a foo object into a std::reference_wrapper, but I end up with a compiler error I don't understand.

#include <functional>
#include <map>

struct foo
{
};

int main()
{
    std::map< int, std::reference_wrapper< foo > > my_map;
    foo a;
    my_map[ 0 ] = std::ref( a );
}

The compiler error is pretty lengthy, but it boils down to this:

error: no matching function for call to ‘std::reference_wrapper<foo>::reference_wrapper()’

What exactly am I doing wrong?

like image 323
qdii Avatar asked Mar 31 '15 08:03

qdii


People also ask

How elements are stored in map?

All the elements in a map are stored in a key-value pair where each key is unique. Sorting is done with the help of keys and the values are associated with each key. Values can be inserted and deleted as and when required.

What does map do in c++?

A C++ map is a way to store a key-value pair. A map can be declared as follows: #include <iostream> #include <map> map<int, int> sample_map; Each map entry consists of a pair: a key and a value.

Which operator is used to associate keys with values in a map data type?

The mapped values in a map can be accessed directly by their corresponding key using the bracket operator ((operator[]).


1 Answers

std::reference_wrapper is not default-constructible (otherwise it would be a pointer).

my_map[0]

creates, if 0 is not already a key in the map, a new object of the mapped type, and for this the mapped type needs a default constructor. If your mapped type is not default-constructible, use insert():

my_map.insert(std::make_pair(0, std::ref(a)));

or emplace():

my_map.emplace(0, std::ref(a));
like image 105
Wintermute Avatar answered Oct 02 '22 10:10

Wintermute