C++ STL 优先级队列获取 bad_alloc

C++ STL priority queue getting bad_alloc

我正在尝试使用 STL 优先级队列,定义为:

template <typename T>
using min_queue = std::priority_queue<T, std::vector<T>, std::greater<T>>;

当运行以下代码:

Label kNN(int k, const Matrix &trainingSet, const std::vector<Label> &trainingLabels, Matrix &evSet, int i1, const DistanceF &f) {
    Timer timer("kNN Timer");
    min_queue<std::pair<double, Label>> distances;

    for (int i = 0; i < trainingSet.rows(); ++i) {
        distances.push(std::pair<double, Label>(f(trainingSet, i, evSet, i1), trainingLabels[i]));
    }

    int i = 0;
    int labels[] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};

    while (!distances.empty() && i < k) {
        labels[(int)distances.top().second]++;
        distances.pop();
        ++i;
    }

    int maximum = 0;

    for (int j = 0; j < 10; ++j) {
        if (labels[j] > maximum) {
            maximum = j;
        }
    }

    return (double)maximum;
}

我收到以下错误:

malloc: *** error for object 0x230000000: pointer being freed was not allocated

问题最终出现在代码的不同部分:复制矩阵时,要复制的行数有误,导致源矩阵 no 的最后一行被复制到目的地矩阵。因此,向量没有正确初始化,并导致错误的分配错误。