0

我有一个优先级队列,其中包含名为 AI 的类的元素,需要该队列中的元素,这些元素可能在队列中较低(优先级较低)。所以,我试图弹出一些元素,直到我得到我选择的元素。一旦我得到我选择的元素,我计划将我临时存储的所有元素推送到一个数组中。我有一个循环,对于每次迭代,我都会在队列中进一步检查我弹出的元素是否是我的选择。这样我在临时数组中有更多数据。当我尝试将此临时数组中的数据推回优先级队列时,就会出现问题。优先级的底层容器是一个向量,调试表明问题出在 stl_queue.h 中,行 std::push_heap(c.begin(), c.end(), comp); (c 是向量)

我知道这可能是错误的方法,我可能应该使用构造函数而不是 malloc 并使用 std:list 而不是优先级队列,但是有人可以让我知道这里发生了什么吗?

while(count < length_of_queue) // Iterate over all elements of queue
{

  A* temp_array = (A *)malloc(count * sizeof(A));;
  for (int i = 0;i<count;i++) // remove count number of elements from queue
  {
      temp_array[i] = priority queue.top();
      priority queue.pop(); // free_list is the priority queue
  }

  A check_element = free_list.top(); // Check if (count+1)th elements satisfies our         
                                     // criteria   
  if (criteria_satisfied)
  {
    priority_queue.pop();
    //freeing the temp_array and pushing back all the elements from temp_array into 
    // priority_queue like done in the else condition
    return check_element;
   }
  else
  {

    for (int i = 0;i<count;i++) // Push back all the elements popped until now
    {
      priority_queue.push(temp_array[i]); // Offending line
    }
    free (temp_array);
  }
  count++
}
4

2 回答 2

1

您的 malloc 行分配了一个足够大的数组来容纳counttype 的对象A,但实际上并没有创建任何对象。当您尝试使用不存在的对象时,会发生未定义的行为(例如,段错误)。

尝试将您的 malloc 替换为std::vector<A> temp_array(count). 这将(有效地)为您提供一组count默认构造的A对象。更重要的是,它会在超出范围时自行释放。

于 2010-07-29T13:35:19.260 回答
1

如果 A 不是 POD,那么使用 malloc 可能会导致各种问题。改用向量:

std::vector<A> temp_array(count);

然后免费将完全消失。

于 2010-07-29T04:32:00.733 回答