0

I am trying to understand the unordered_map assignment, I get the following error: no matching function for call to std::pair<foo, foo>::pair(), according to the doc for unordered_map operator[]:

If k does not match the key of any element in the container, the function inserts a new element with that key and returns a reference to its mapped value.

So I am trying to assign an object (from make_pair) to this reference, which I am guessing is not allowed. However with the pair<int,int>, it works, then I am wondering if I must declare some other operators for foo to make this work.

#include <bits/stdc++.h>
using namespace std;

struct foo {
  int n;
  foo(int n): n(n) {};
};

int main(){
  unordered_map<int, pair<foo,foo>> m;
  //m[3] = make_pair(foo(1),foo(2));         <--- error here

  unordered_map<int, pair<int,int>> ii;
  ii[3] = make_pair(1,2);
}
6
  • Have you read and tried to understand the error message? Commented Mar 20, 2020 at 2:25
  • -bitmask, yes I have been staring at it for a while, I would post it here (quite long), if someone can help me decipher it, that would be great. Commented Mar 20, 2020 at 2:34
  • Well, it would be useful to be able to help you decipher it, if you'd post it. Commented Mar 20, 2020 at 14:31
  • -bitmask, I posted a follow up question, it is not the whole set of errors, let me know if I should add more/less. (stackoverflow.com/questions/60776989/…) Commented Mar 20, 2020 at 15:26
  • I provided you with a step-by-step guide of how to understand such an error under that question. Hope it helps. Commented Mar 20, 2020 at 17:03

1 Answer 1

2

The problem is that operator [] might have to construct a value object, in your case std::pair<foo, foo>. Since foo doesn't have a default constructor, it can't construct the default std::pair.

You can either provide a default constructor for foo (including adding a default value for n), or you'll have to use another method to insert values into m.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks Stephen, if I use m.insert(make_pair(key,make_pair(foo(1),foo(2)))), then the default constructor is not invoked, is that correct? Or are there better ways to do this, thanks!
You're correct. You probably want to do some error-checking, but otherwise your suggestion is fine.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.