0

As we know, both of these ways to assign are possible. Why we still have std::make_pair?

std::pair<int, char> myPair1 = { 1,'a' };
std::pair<int, char> myPair2 = std::make_pair(1, 'a');

I'm not here to criticize the syntax. I just really want to know what's the advantage for us to use std::make_pair instead of directly using the curly braces.

Actually, I think the only advantage is that it can make our code more readable, like you're passing the parameter with std::make_pair instead of the curly braces. It makes it easier to tell that you're passing a pair. Since the curly brace can refer to something more, like a tuple or array.

Drew Dormann
  • 59,987
  • 13
  • 123
  • 180
VIRJIRRR
  • 9
  • 1
  • 3
    Dup of https://stackoverflow.com/questions/9270563/what-is-the-purpose-of-stdmake-pair-vs-the-constructor-of-stdpair? – 康桓瑋 Mar 27 '23 at 14:02
  • 1
    @康桓瑋 the second answer, in particular. Specifically not the accepted answer. – Drew Dormann Mar 27 '23 at 14:04
  • 3
    _why do we still have std::make_pair?_ Also, so as not to break existing code, I guess – Paul Sanders Mar 27 '23 at 14:06
  • 2
    If they removed every feature that was no longer considered the best way to do something, we'd have a pretty nice language, but that language's compiler wouldn't be able to compile most of the C++ code out there anymore and it would probably need to be named something else. – Jeremy Friesner Mar 27 '23 at 14:10
  • Do note, that for `std::pair myPair2 = std::make_pair(1, 'a');`, we can save a lot of typing by using `auto myPair2 = std::make_pair(1, 'a');` – NathanOliver Mar 27 '23 at 14:12
  • Nothing is ever deprecated for cosmetic reasons. – molbdnilo Mar 27 '23 at 14:20
  • 3
    `make_pair` is not without its uses in C++17 still. We cannot omit arguments and do `pair{"aa", 1}` - it's all or nothing. So if I really want a `std::string` there instead of a character pointer, while still deducing the second type, `std::make_pair("aaa", 1)` has its utility and charm. – StoryTeller - Unslander Monica Mar 27 '23 at 14:43
  • The answer from Jeremy Friesner is awesome.Thanks a lot. – VIRJIRRR Mar 30 '23 at 14:57

0 Answers0