mardi 3 août 2021

How to use insert_or_assign in map for custom class?

I am using insert_or_assign of c++17 https://en.cppreference.com/w/cpp/container/map/insert_or_assign this says that the mapped value is constructed using rvalue reference i.e. std::move.

Here is my custom class, which I am using as a key. Next is the value, which I am using as vector. While I am trying to use uniform initialization, I get the compilation error. Also, if I use std::pair still I get an error. I am unable to understand what that error really means? Here is the error and the code.

Without std::pair

g++ -std=c++17 map.cpp -o map.out
map.cpp: In function ‘int main(int, char**)’:
map.cpp:51:66: error: no matching function for call to ‘std::map<MyData, std::vector<std::__cxx11::basic_string<char> > >::insert_or_assign(<brace-enclosed initializer list>, <brace-enclosed initializer list>)’
   51 |    studentClasses.insert_or_assign( {36, "Naja"s}, {"class 5th"s});

With std::pair, I get the following -

map.cpp:42:76: error: no matching function for call to ‘make_pair(<brace-enclosed initializer list>, <brace-enclosed initializer list>)’
   42 |    studentClasses.insert_or_assign( std::make_pair({36, "Naja"}, {"year 5"}));
      |     

                                                                   ^

Now, here is the entire code ,

#include <iostream>
#include <map>
#include <vector>

using namespace std;

class MyData
{
    private:
        int age;
      string name;
   public:
      int getAge()
      {
         return age;
      }
      string& getName()
      {
        return name; 
      }
      MyData(int age_val, string name_val): age(age_val), name(name_val) 
      {
         cout<<"Constructor invoked"<<endl;
      }
      bool operator <(const MyData &other) const
      {
         return age < other.age;
      }
};

int main(int argc, char **argv)
{
   std::map<MyData, vector<string>> studentClasses;
   studentClasses.insert_or_assign( std::make_pair({36, "Naja"}, {"year 5"})); 
   //studentClasses.insert_or_assign( {36, "Naja"s}, {"class 5th"s}); 
   return 0;
}

Aucun commentaire:

Enregistrer un commentaire