简体   繁体   English

这个 function 中 std::bad_alloc 的原因是什么?

[英]What is the reason for std::bad_alloc in this function?

I have written below C++ function which loops through an integer vector.我在下面写了 C++ function 循环通过 integer 向量。 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.但是,每当我尝试运行时,我都会收到“std::bad_alloc”。 The error is gone when remove the line "flag=true".删除“flag=true”行后错误消失。 I will need it to work so that the while loop breaks.我需要它来工作,以便 while 循环中断。 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;
}

Consider the input [0, 1] .考虑输入[0, 1]

The minimum is 0, so you subtract 0 from every element (does nothing).最小值为 0,因此您从每个元素中减去 0(什么都不做)。 Since the second element is 1 ( not 0 ) you set flag = true .由于第二个元素是 1 (不是 0 )你设置flag = true

Nothing has changed in this loop except you have pushed back to the result vector.除了您推回result向量外,此循环中没有任何变化。 So the loop will repeat until vector runs out of memory (or exceeds its max_size ).因此循环将重复,直到vector用完 memory (或超过其max_size )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM