Home > Back-end >  Why is it not correct when constructor is called recursively?
Why is it not correct when constructor is called recursively?

Time:09-18

This is leetcode 341. When I write like this, it is correct:

class NestedIterator {
public:
    vector<int> flatted;
    int current=0;
    NestedIterator(vector<NestedInteger> &nestedList) {
        flatten(nestedList);
    }
    
    void flatten(vector<NestedInteger> &nestedList)
    {
        for(NestedInteger i:nestedList)
        {
            if(i.isInteger())
                flatted.push_back(i.getInteger());
            else
                flatten(i.getList());
        }
    }
    
    int next() {
        current  ;
        return flatted[current-1];
    }
    
    bool hasNext() {
        if(current<flatted.size())
            return true;
        else
            return false;
    }
};

But, if I write it like this, it is not correct:

class NestedIterator {
public:
    vector<int> flatted;
    int current=0;
    NestedIterator(vector<NestedInteger> &nestedList) {
        for(NestedInteger i:nestedList)
        {
            if(i.isInteger())
                flatted.push_back(i.getInteger());
            else
                NestedIterator(i.getList());
        }
    }
};

The only difference is that in method 2, I call the constructor recursively. Why is it not correct?

CodePudding user response:

As others have mentioned, the iterator you create below the loop is not working because it has its own list that it populates and since you never keep any reference to it, after it is finished, it goes out of scope and is destroyed.

Try this instead:

class NestedIterator {
public:
    vector<int> flatted;
    int current=0;
    NestedIterator(vector<NestedInteger> &nestedList) {
        for(NestedInteger i:nestedList)
        {
            if(i.isInteger())
                flatted.push_back(i.getInteger());
            else {
                auto iter = NestedIterator(i.getList());
                this->flatted.insert(this->flatted.end(), iter.flatted.begin(), iter.flatted.end()); // here we copy the vector from this iterator
            }
        }
    }
};

The goal above is to copy the vector from the temporary iterator, into the current one

  • Related