I have written below C++ function which loops through an integer vector. With each pass it subtracts smallest number from all its numbers. It is supposed to return the number of non zero elements at each pass(this is stored in the vector result and is returned). However I am getting "std::bad_alloc" evertime I try to run. The error is gone when remove the line "flag=true". I will need it to work so that the while loop breaks. Help me fix this.
vector<int> cutTheSticks(vector<int> arr) {
int flag=true, min, count;
vector<int> result;
while(flag)
{
min = arr[0];
flag = false;
count = 0;
for(int i=1; i<arr.size(); i++)
{
if(arr[i]<min)
{
min=arr[i];
}
}
for(int i=0; i<arr.size(); i++)
{
if(arr[i]!=0)
{
count++;
flag = true;
}
arr[i] = arr[i]-min;
}
result.push_back(count);
}
return result;
}