mardi 6 septembre 2022

How to use std::reference_wrapper in std::map for both key and value? [duplicate]

I have a map that uses std::pair as key and int as value:

std::map<std::pair<int, int>, int> mymap;

I want to create a "view" on this map, so that I can use a different comparator with the goal of changing the iteration order without having to make a copy of the map. Based on the example provided here I thought the correct way to achieve my goal was to user std::reference_wrapper like so:

std::map<std::reference_wrapper< std::pair<int, int> >, std::reference_wrapper<int>, MyComp> mymap_view(mymap.begin(), mymap.end());

This does not compile with an (for me*) obscure error:

/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/c++/v1/map:1226:17: error: no matching member function for call to 'insert'
                insert(__e.__i_, *__f);
                ^~~~~~
/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/c++/v1/map:1011:13: note: in instantiation of function template specialization 'std::map<std::reference_wrapper<std::pair<int, int>>, std::reference_wrapper<int>, MyComp>::insert<std::__map_iterator<std::__tree_iterator<std::__value_type<std::pair<int, int>, int>, std::__tree_node<std::__value_type<std::pair<int, int>, int>, void *> *, long>>>' requested here
            insert(__f, __l);
            ^
main.cpp:66:98: note: in instantiation of function template specialization 'std::map<std::reference_wrapper<std::pair<int, int>>, std::reference_wrapper<int>, MyComp>::map<std::__map_iterator<std::__tree_iterator<std::__value_type<std::pair<int, int>, int>, std::__tree_node<std::__value_type<std::pair<int, int>, int>, void *> *, long>>>' requested here
    std::map<std::reference_wrapper< std::pair<int, int> >, std::reference_wrapper<int>, MyComp> mymap_view(mymap.begin(), mymap.end());
... a number of candidates considered and reasons why not viable ...

The use of MyComp seems of no influence: leaving it out results in the same error as far as I can tell.

What am I missing here?


*I'm trying to get back to C++ after many years of absence (according to my colleague, I'm so rusty that tetanus shots are required), so maybe I'm missing something obvious. There is a number of questions related to std::map, std::reference_wrapper, etc. and I think I have checked all of them, but without finding an answer.

Aucun commentaire:

Enregistrer un commentaire