Error when using std::vector::size to create another vector

Advertisements

I am learning DSA and while practising my LeetCode questions I came across a question-( https://leetcode.com/problems/find-pivot-index/).
Whenever I use vector prefix(size), I am greeted with errors, but when I do not add the size, the program runs fine.
Below is the code with the size:

class Solution {
public:
    int pivotIndex(vector<int>& nums) {
        //prefix[] stores the prefix sum of nums[]
        vector<int> prefix(nums.size());
        int sum2=0;
        int l=nums.size();
        //Prefix sum of nums in prefix: 
        for(int i=0;i<l;i++){
            sum2=sum2+nums[i];
            prefix.push_back(sum2);
        }
        //Total stores the total sum of the vector given 
        int total=prefix[l-1];
        for(int i=0; i<l;i++)
        {   
            if((prefix[i]-nums[i])==(total-prefix[i]))
            {
                return i;
            } 
        }
        return -1;
    }
};

I would really appreciate if someone could explain this to me.
Thanks!

>Solution :

If you use vector constructor with the integer parameter, you get vector with nums.size() elements initialized by default value. You should use indexing to set the elements:

...
for(int i = 0; i < l; ++i){
    sum2 = sum2 + nums[i];
    prefix[i] = sum2;
}
...

If you want to use push_back method, you should create a zero size vector. Use the constructor without parameters. You can use reserve method to allocate memory before adding new elements to the vector.

Leave a ReplyCancel reply