Search code examples
c++vectorconstructordefault-constructorcopy-assignment

Could someone explain the meaning of vector<Node*>()


I'm solving the Clone Graph in Leetcode, but I encountered a problem inside the following codes

 class Node {
public:
    int val;
    vector<Node*> neighbors;
    Node() {
        val = 0;
        neighbors = vector<Node*>();
    }
    Node(int _val) {
        val = _val;
        neighbors = vector<Node*>();
    }
    Node(int _val, vector<Node*> _neighbors) {
        val = _val;
        neighbors = _neighbors;
    }
};

what does it mean by the statement neighbors = vector<Node*>();. More specifically, vector<Node*>(). Why is it followed by parentheses?


Solution

  • Actually this statement in the constructors of the class Node

    neighbors = vector<Node*>();
    

    is redundant.

    There is used the move assignment operator that assigns an empty vector created by calling the default constructor vector<Node*>() of the class std::vector<Node *> to the already created empty vector neighbors that is a data member of the class Node.

    You may remove this statement from the constructors of the class Node. In fact it has no effect.