make_pair() in C++

前端 未结 2 1029
庸人自扰
庸人自扰 2021-01-29 12:35

I was doing the problem 337 from leetcode. This is the code I implemented.

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *              


        
2条回答
  •  萌比男神i
    2021-01-29 13:01

    When you have a

    unordered_map& memo
    

    and you want to insert an element:

    memo.insert(make_pair(root, result));
    

    There are several overloads that would match. My guess (but please think about this a bit) is that you want the one taking a const value_type& as argument. In that case, just construct the pair doing exactly that:

    memo.insert(unordered_map::value_type(root, result));
    

    The sole reason why you use make_pair() is to let the compiler pick the template parameters (less typing, a generic pair ctor). If you want to specify the types explicitly, you can use the plain pair ctor. In this case though, I'd consider it an implementation detail of unordered_map and instead use its nested typedef. That typedef is btw. std::pair!

    All this leaves me with one question only: Why not use memo[root] = result?

提交回复
热议问题