Vinu
Vinu

Reputation: 179

Move insertion with unordered_map having multiple values

I tried the below code for move and initializer list insertions. The later works but not the move insertion. Can someone help me with the right solution here ?

#include <iostream>
#include <iostream>
#include <string>
#include <unordered_map>
using namespace std;


int main ()
{
  std::unordered_map<std::string,std::pair<double, double>>
              myrecipe;

  myrecipe.insert (std::make_pair<std::string,std::make_pair<double,double>>("eggs",(1.0,6.0)));
  myrecipe.insert ( {{"sugar",{0.8, 1.0}},{"salt",{0.1, 2.0}}} );   

  std::cout << "myrecipe contains:" << std::endl;
  for (auto& x: myrecipe)
    std::cout << x.first << ": " << x.second.first << ":" << x.second.second << std::endl;

  std::cout << std::endl;
  return 0;
}

Upvotes: 0

Views: 603

Answers (3)

Frodyne
Frodyne

Reputation: 3983

This line has a few problems:

myrecipe.insert (std::make_pair<std::string,std::make_pair<double,double>>("eggs",(1.0,6.0)));

The type you want to insert is a std::pair<std::string, std::pair<double, double>>, but that is not what you are making here. This is how to make it work with make_pair:

myrecipe.insert(std::make_pair<std::string, std::pair<double, double>>("eggs", std::make_pair<double, double>(1.0, 6.0)));

Or in a more readable format, that relies on template argument type deduction:

myrecipe.insert(std::make_pair("butter", std::make_pair(2.0, 3.0)));

Godbolt link, so you can see it work.

Upvotes: 3

tommy
tommy

Reputation: 182

If you change that line to myrecipe.insert ({"eggs",{1.0,6.0}}); it should work as intended

Also, std::make_pair<double,double> should not appear as a template parameter since it is not a type but a function that returns an object.

Upvotes: 0

RoQuOTriX
RoQuOTriX

Reputation: 3001

You need to make the pair on the doubles, not the complete insert:

myrecipe.insert(("eggs",std::make_pair<double,double>(1.0,6.0)));

To clarify:
<std::string,std::pair<double, double>> is not a std::pair, it is a key-value pair (sic!).
Your std::pair<double, double> instead is a "real" std::pair (or someone could say a 2-tuple) which can be used in C++ as a std::pair. Therefore you need the std::make_pair_call

Upvotes: 0

Related Questions