0
我試圖使這個mergesort函數來排序向量或單詞節點(包含字長,出現次數和單詞本身)它似乎進入合併函數一次,然後程序失敗,任何想法?C++合併排序不會合並?
bool Utility::mergeSort_occurences(vector<Word> &invector){
if (invector.size() <= 1){
return true;
}
vector<Word> left, right;
int middle = (invector.size()/2);
for(int i = 0 ; i < middle ; i++){
left.push_back(invector[i]);
}
for(int i = middle ; i < invector.size() ; i++){
right.push_back(invector[i]);
}
mergeSort_occurences(left);
mergeSort_occurences(right);
invector = mergeOccurences(left, right);
return true;
}
vector<Word> Utility::mergeOccurences(vector<Word> &left, vector<Word> &right){
vector<Word> mergelist;
while(left.size() > 0 || right.size() > 0){
if(left.size() > 0 && right.size() > 0){
if(left[0].getOccurences() <= right[0].getOccurences()){
mergelist.push_back(left[0]);
left.erase(left.begin());
}else{
mergelist.push_back(right[0]);
right.erase(right.erase(right.begin()));
}
}
else if(left.size() > 0){
mergelist.push_back(left[0]);
left.erase(left.begin());
}
else if(right.size() > 0){
mergelist.push_back(right[0]);
right.erase(right.erase(right.begin()));
}
}
return mergelist;
}
是的 - 你可以調試它。使用向量中的一個小數據集,使用調試器運行代碼。說四個價值。然後,應該很容易地找出問題的所在,比試圖通過盯着由其他人寫的一頁複雜的矢量/數組處理代碼來發現問題要容易得多。 – 2012-04-10 01:18:55