Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading