Why is it taking more memory when I access an array directly with iterators instead of just copying the vector

Why is it taking more memory when I access an array directly with iterators instead of just copying the vector

I implemented a function to return the Pascal Tree of numRows rows in 2 ways:

// Making a copy of the last element 
class Solution {
public:
    vector<vector<int>> generate(int numRows) {
        vector<vector<int>> tri;
        tri.emplace_back(vector<int>(1,1));
        for(int i=2;i<=numRows;i++){
            vector<int> row(i,1);
            vector<int> last = tri.back(); // Simply making a copy of the last Array
            for(int j=1;j<i-1;j++){
                row[j]=last[j]+last[j-1];
            }
            tri.push_back(row);
        }
        return tri;
    }
};

Runtime: ~0ms
Memory: 9.54MB

// Using an iterator to get the value at some location
class Solution {
public:
    vector<vector<int>> generate(int numRows) {
        vector<vector<int>> tri;
        tri.emplace_back(vector<int>(1,1));
        for(int i=2;i<=numRows;i++){
            vector<int> row(i,1);
            auto last = (tri.end()-1)->begin(); // here
            for(int j=1;j<i-1;j++){
                row[j]=*(last)+*(++last);
            }
            tri.push_back(row);
        }
        return tri;
    }
};

Runtime: ~3ms
Memory: 9.61MB

I fail to see why the second implementation is slower and more importantly why it takes up more space even when, as I understand, there should not be any need to allocate any significant amount of memory.

The stats are from leetcode if that is of any significance.

Answer

The slight memory increase in the second version comes from extra temporary variables and iterator handling inside the loop. While no extra heap memory is allocated, the compiler uses more stack or register space, causing marginally higher usage. The difference is very small and likely due to normal runtime variation.

Enjoyed this question?

Check out more content on our blog or follow us on social media.

Browse more questions