What is the purpose of std::make_pair vs the constructor of std::pair?

后端 未结 7 1313
借酒劲吻你
借酒劲吻你 2020-12-04 06:04

What is the purpose of std::make_pair?

Why not just do std::pair(0, \'a\')?

Is there any difference between the tw

7条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-04 06:33

    The difference is that with std::pair you need to specify the types of both elements, whereas std::make_pair will create a pair with the type of the elements that are passed to it, without you needing to tell it. That's what I could gather from various docs anyways.

    See this example from http://www.cplusplus.com/reference/std/utility/make_pair/

    pair  one;
    pair  two;
    
    one = make_pair (10,20);
    two = make_pair (10.5,'A'); // ok: implicit conversion from pair
    

    Aside from the implicit conversion bonus of it, if you didn't use make_pair you'd have to do

    one = pair(10,20)
    

    every time you assigned to one, which would be annoying over time...

提交回复
热议问题