-2

I want to create a pair in C++

int x=3;
int y =4;
std::pair<int,int> mypair = std::make_pair<int,int>(x,y);

But i get this error:

 error: no matching function for call to ‘make_pair(int&, int&)’
     std::pair<int,int> mypair = std::make_pair<int,int>(x,y);

On the other hand, if I use

std::pair<int,int> mypair = std::make_pair<int,int>(3,4);

then it works. Any explanation on ths? And how to make the first case above work so one can create a pair (x,y) wihtout pain?

zell
  • 9,830
  • 10
  • 62
  • 115
  • Possible duplicate of https://stackoverflow.com/questions/9641960/c11-make-pair-with-specified-template-parameters-doesnt-compile. – OM Bharatiya Mar 31 '20 at 16:34

2 Answers2

3

Change to:

std::pair<int,int> mypair = std::make_pair(x,y);

Explanation here

Community
  • 1
  • 1
101010
  • 41,839
  • 11
  • 94
  • 168
2

To make your first case work you can do

std::pair<int, int> mypair{x, y};
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
  • Thanks. What is that strange syntax? – zell Jun 25 '15 at 14:58
  • That would be [uniform initialization](https://stackoverflow.com/questions/7612075/how-to-use-c11-uniform-initialization-syntax) – Cory Kramer Jun 25 '15 at 14:59
  • This is C++11 initialization. If you are pre C++11 you can do `std::pair mypair = std::pair(x,y)` (to avoid the statement to look like a function declaration) – 463035818_is_not_an_ai Jun 25 '15 at 14:59
  • 1
    @tobi303 MVP doesn't apply here because `x` and `y` aren't types. – TartanLlama Jun 25 '15 at 15:00
  • @TartanLlama oh yes, I was just wondering why he used the fancy brackets and then I was too fast in writing (well, faster than thinking) – 463035818_is_not_an_ai Jun 25 '15 at 15:02
  • I'd like to say, make_pair was introduced so you could create pair without specifying redundantly template arguments (ie: having to type ). If you too want to avoid typing redundant stuff, I'd recommend using the auto keyword for mypair's type and initialize it with a make_pair – KABoissonneault Jun 25 '15 at 15:05