samedi 27 octobre 2018

Why cannot I assign a vector v in a struct?

I did some exercise on the leetcode, I find out that while I try to assign a new vector to a member in a struct, it doesn't work.

The problem happens at the 8th line of the deserialize function. I have put my question here.

/*
// Definition for a Node.
class Node {
public:
    int val = NULL;
    vector<Node*> children;

    Node() {}

    Node(int _val, vector<Node*> _children) {
        val = _val;
        children = _children;
    }
};
*/
class Codec {
public:

    // Encodes a tree to a single string.
    string serialize(Node* root) {
        if (!root) return "NULL";
        stringstream ss;
        dfs(ss, root);
        return ss.str();
    }

    // Decodes your encoded data to tree.
    Node* deserialize(string data) {
        if (data == "NULL") return nullptr;
        stringstream ss(data);
        vector<Node*> res = deserialize(ss);
        return res.front();

    }
private:
    void dfs(stringstream& ss, Node* root) {
        if (!root) {
            return;
        }
        ss << root->val << " ( ";
        for (Node* child : root->children) {
            dfs(ss, child);
        }
        ss << " ) ";
    }
    vector<Node*> deserialize(stringstream& ss) {
        vector<Node*> res;
        string s;
        while (ss.good()) {
            ss >> s;
            if (s == ")") return res;
            else if (s == "(") {
                vector<Node*> children = deserialize(ss);
                // Here is the problem, while I can use the insert to assign a new value to the vector in a struct, the directly assignment doesn't work
                res.back()->children.insert(res.back()->children.end(), children.begin(), children.end());
                // The following expression doesn't work
                // res.back()->children = children;
            } else {
                Node* node = new Node();
                node->val = stoi(s);
                res.push_back(node);
            }
        }
        return res;
    }
};

// Your Codec object will be instantiated and called as such:
// Codec codec;
// codec.deserialize(codec.serialize(root));

This is so wired. Could someone help me to figure out why this one happened?

Aucun commentaire:

Enregistrer un commentaire