c++ - 使用优先级队列时出现段错误

标签 c++ reference vector constants priority-queue

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

我知道这可能是错误的方法,我可能应该使用构造函数而不是 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++
}

最佳答案

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

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

关于c++ - 使用优先级队列时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3358853/

相关文章:

c++ - 为什么 C++ 中的 "integer"数据类型能够保存 "true"或“false; boolean 值”

c++ - 从常量引用初始化非常量引用

javascript - 混淆对 Javascript 中具有属性的函数的引用

c++ - 我如何使用 std :vector's erase() function properly?

java - 如何将角度转换为 vector

c++ - 如何组成一个矩阵来执行世界坐标的等轴测(二轴测)投影?

c++ - SFML 纹理变换(放大)

c++ - 找到最小化 sigma(abs(a[i]+c[i])) 的递增序列 a[]

c++ - 指针、引用还是智能指针?

python - 如何将 Numba "@vectorize"ufunc 与结构化 Numpy 数组一起使用?