-2

This is an easy category question on leetcode. The solution works fine on their compiler, but I just wanted to learn that while coding the same thing on my compiler, What should I pass in the main function so that the vector function gets it?

#include<bits/stdc++.h>
using namespace std;

class Solution {
public:
    vector<int> runningSum(vector<int>& nums)
    {
        int n=nums.size();
       int sum=0;
       vector<int>arr;
       for(int i=0; i<n; i++){
        sum = sum + nums[i];
        arr.push_back(sum);
       }
    }
    return arr;
};
int main(){
    int size;
    cin>>size;
    int nums[size];
    int i;
    for(i=0; i<size; i++)
        cin>>nums[i];
    
    Solution ob;
    cout<<ob.runningSum(???);
}

  • 6
    Don't use non-standard VLA (Variable-Length Array) `int nums[size];`. The function expects `vector`, so use [`std::vector`](https://en.cppreference.com/w/cpp/container/vector). – MikeCAT Jul 26 '22 at 13:25
  • 6
    you should pass a vector. Dont confuse coding challenges sites with places to learn a language. Thats not what they are. They are rather the opposite, they assume you know the basics and then they add a mass of bad practices on top of that – 463035818_is_not_an_ai Jul 26 '22 at 13:26

2 Answers2

3

Like the code says you need a vector

int main(){
    int size;
    cin>>size;
    vector<int> nums;
    int i;
    for(i=0; i<size; i++)
    {
        int x;
        cin>>x;
        nums.push_back(x);
    }
    
    Solution ob;
    cout<<ob.runningSum(nums);
}
john
  • 85,011
  • 4
  • 57
  • 81
1

int nums[size]; with non-const variable size is called Variable-Length Array (VLA). This is not in the C++ standard.

Since the function accepts vector, you should use std::vector.

int main(){
    int size;
    cin>>size;
    //int nums[size];
    std::vector<int> nums(size); // allocate a vector with size elements
    int i;
    for(i=0; i<size; i++)
        cin>>nums[i];
    
    Solution ob;
    //cout<<ob.runningSum(???);
    cout<<ob.runningSum(nums); // and pass the vector
}
MikeCAT
  • 73,922
  • 11
  • 45
  • 70