c++ - std::vector 超出最小堆范围:C++

标签 c++ algorithm vector heap outofrangeexception

我有一段时间没有处理这段代码(或任何其他编码项目),所以虽然我知道代码基本上有什么问题,但我一直很难找到 vector 的确切位置超出范围。我整个早上都在运行 gdb,但无济于事。我正在尝试用 C++ 中的 vector “theData”创建一个最小堆。

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

using std::vector;
using std::cin;
using std::cout;
using std::swap;
using std::pair;
using std::make_pair;

class HeapBuilder {
     private:
        vector<int> data_;
        vector< pair<int, int> > swaps_;

 void WriteResponse() const {
      cout << swaps_.size() << "\n";
for (int i = 0; i < swaps_.size(); ++i) {
  cout << swaps_[i].first << " " << swaps_[i].second << "\n";
       }
}

 void ReadData() {
        int n;
        cin >> n;
        data_.resize(n);
        for(int i = 0; i < n; ++i)
         cin >> data_[i];
}

  void makeMinHeap(vector<int> &theData, int i, int n) {
    int minIndex;
    int left = 2*i;
    int right = 2*i + 1;
      if (left < n && theData.at(left) < theData.at(i)) {
        minIndex = left;
    }
    else if (right < n && theData.at(right) < theData.at(i)) {
        minIndex = right;
    }

if (minIndex != i) {
    swap(theData.at(i), theData.at(minIndex));
    swaps_.push_back(make_pair(i, minIndex));
    makeMinHeap(theData, minIndex, n);
    }
}

  void GenerateSwaps() {
    swaps_.clear();
    int size = data_.size();
    for (int i = (size/2); i >= 0; i--) {
    makeMinHeap(data_, i, size);
     }

  }

 public:
  void Solve() {
     ReadData();
     GenerateSwaps();
     WriteResponse();
  }
};

int main() {
  std::ios_base::sync_with_stdio(false);
  HeapBuilder heap_builder;
  heap_builder.Solve();
  return 0;
}

最佳答案

您没有检查 minIndex。 看看当你的 left<=n 和 right <=n 都失败时会发生什么,很可能是在整个递归即将停止时,因为你只是检查

 minIndex != i
// ^-- default each time is garbage which in case last>n && right>n leaves it garbage
// hence when it comes to
if(minIndex!=i){
// It's actually true where it was suppose to break out n thus throws out_of_range
}

快速简单的解决方案是添加一个 flagcheck

bool flagcheck = false;
if(){ flagcheck = true; }
else if(){ flagcheck = true; }
if(minIndex!=i && flagcheck){}

关于c++ - std::vector 超出最小堆范围:C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37222079/

相关文章:

C++ - 奇怪的事情,输入被颠倒了

c++ - C++ 中的 lambda 方程

c++ - 传递参数并给它们赋值会导致运行时错误

algorithm - 两个不同长度的排序数组的中位数

visual-studio - 如何搜索文件以查找整数

c++ - vector 迭代器和模板函数

c++ - 编码是否影响 strstr() (及相关函数)的结果

c++ - 如何加速 C++ 中的 CYK 算法?

寻找最佳预测权重的算法

c++ - 下层 std::vector<std::string>