我忽略了在這段代碼(或任何其他編碼項目)上工作了一段時間,所以雖然我知道代碼基本錯誤,我一直很難找到矢量超出範圍的確切位置。我一直在上面運行gdb而無濟於事。我試圖用C++中的矢量「theData」創建一個最小堆。std ::向量超出最小堆的範圍:C++
#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;
}
它不應該被留下'
sshashank124
我寫了這樣的說法年初的時候,我試圖調試代碼,並返回給它經過一番研究。不過,這個bug並沒有什麼不同。 – Anonymous
請嘗試爲[MVCE](http://stackoverflow.com/help/mcve)顯示足夠的代碼。該問題的代碼無法編譯。例如,變量'swaps_'和'data_'永遠不會被聲明。如果您提供了破壞功能的測試數據,即使中斷了任何數據,也會有所幫助。 –