C++ 优先级队列推送在 Visual Studio 2017 中导致“...已停止工作”

C++ priority queue push causing '...has stopped working' in Visual Studio 2017

尝试编写一个简单的程序,使用 C++ 创建一个优先级队列并向其添加一个结构。这是我的代码:

main.cpp:

#include "stdafx.h"
#include <iostream>
#include <vector>
#include <queue>

#include "defs.h"

using namespace std;

int main()
{ 
    priority_queue<BinaryTreeNode*, vector<BinaryTreeNode*>, nodeCmp>* priority = {};

    /* Create Test Data */
    BinaryTreeNode* node1 = new BinaryTreeNode();
    node1->letter = ' ';
    node1->freq = 134;

    priority->push(node1);

    delete node1;
    delete priority;

    return 0;
}

在defs.h中:

#include "stdafx.h"
#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

/* 
 * Node structure for Binary Tree 
 */
struct BinaryTreeNode
{
    char letter;
    int freq;
    BinaryTreeNode* left = NULL;
    BinaryTreeNode* right = NULL;
};

/* 
 * Comparison function for priority queue - prioritises lowest frequency letters
 */
struct nodeCmp
{
    bool operator() (const BinaryTreeNode* left, const BinaryTreeNode* right) const
    {
        return left->freq > right->freq;
    }
};

我在 Visual Studio 2017 年使用 C++。我已经使用 {} 初始化了队列,因为如果不这样做,我会遇到另一个错误。我也尝试过动态分配为节点 freq 和 letter 设置的 char 和 int 值,但也没有任何作用。

删除 main 中的 priority->push(node1) 行可防止出现“...已停止工作”。

我也尝试过 Google 并搜索堆栈溢出,但没有找到任何可以解决我的问题的方法。

在此先感谢您的帮助。

您的程序崩溃的原因是因为以下行

priority_queue<BinaryTreeNode*, vector<BinaryTreeNode*>, nodeCmp>* priority = {};

您正在将优先级创建为指针并将其分配给 null。

然而,这个程序的错误不仅仅是这一行。使用容器很大一部分是为了避免显式内存allocation/deallocation。 SO 上有很多关于此的主题,因此请好好阅读。

对于您正在做的事情,没有理由显式地动态分配 priority_queue 对象。到目前为止,也不需要显式动态分配节点。

实际上您的程序会 re-written 更像下面这样。新的已经没有了,因为它们不是必需的。

#include <algorithm>
#include <iostream>
#include <queue>
#include <vector>

struct BinaryTreeNode {
    char letter;
    int freq;
};

struct nodeCmp
{
    bool operator() (const BinaryTreeNode& left, const BinaryTreeNode& right) const
    {
        return left.freq > right.freq;
    }
};

int main()
{ 
    std::priority_queue<BinaryTreeNode, std::vector<BinaryTreeNode>, nodeCmp> priority;

    /* Create Test Data */
    BinaryTreeNode node1;
    node1.letter = ' ';
    node1.freq = 134;

    priority.push(node1);

    return 0;
}

此行不创建优先级队列:

priority_queue<BinaryTreeNode*, vector<BinaryTreeNode*>, nodeCmp>* priority = {};

它创建了一个指针,它可以指向一个优先级队列,但最初不是(它是一个空指针)。当您随后尝试将某些内容推送到 non-existing 优先级队列时,您遇到了问题。

最小的修复是实际创建一个 priority_queue 并指向它,即将上面的行更改为:

priority_queue<BinaryTreeNode*, vector<BinaryTreeNode*>, nodeCmp>* priority =
    new priority_queue<BinaryTreeNode*, vector<BinaryTreeNode*>, nodeCmp>;

这应该可以解决崩溃问题(这就是 'has stopped working' 的意思),尽管您的程序不会是通常被认为好的风格(因为除其他问题外,您甚至不需要动态分配这种情况)。