c++constructorlist-initialization

how to understand list initialization in C++ when use it to construct class object?


As we all know, list initialization is introduced to C++ from C++11. In most cases, it is easy to understand. However, when using list initialization to construct a class object, it always makes me confused.

I don't understand how the list initialization works in the following code and how it generates Status objects. From push document, we can know its argument type is const Status& value or Status&& value. so in q.push({node->val, node}), {node->val, node} will be cast to Status. I don't know how that is completed.

Anyone can help? Any help is appreciated.

// This is a code snippet from the official LeetCode solution.
class Solution {
public:
    struct Status {
        int val;
        ListNode *ptr;
        bool operator < (const Status &rhs) const {
            return val > rhs.val;
        }
    };

    priority_queue <Status> q;

    ListNode* mergeKLists(vector<ListNode*>& lists) {
        for (auto node: lists) {
            if (node) q.push({node->val, node});
        }
        ListNode head, *tail = &head;
        while (!q.empty()) {
            auto f = q.top(); q.pop();
            tail->next = f.ptr; 
            tail = tail->next;
            if (f.ptr->next) q.push({f.ptr->next->val, f.ptr->next});
        }
        return head.next;
    }
};

Solution

  • The answer has already been pointed out by developers in the comments. To make it easier for people who are confused about this question to understand the answer. I'll restate the answer from the comments here.

    The process of passing actual arguments to function parameters is the initialization of the parameters, not the assignment. And Status is an aggregate type(according to aggregate initialization), so in statement q.push({node->val, node}) there is an aggregate initialization that is using {node->val, node} to initialize aggregate type Status.