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(???);
}
CodePudding user response:
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);
}
CodePudding user response:
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
}