c ++合并排序不会合并?

时间:2012-04-10 01:03:58

标签: c++ sorting vector mergesort

我试图让这个mergesort函数对一个矢量或单词节点进行排序(包含单词长度,出现次数和单词本身)它似乎进入合并函数一次,然后程序失败,任何想法?

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;
}

1 个答案:

答案 0 :(得分:1)

您的right.erase(right.erase(right.begin()));代码看起来很狡猾。 erase函数将一个迭代器返回给已删除元素的后继者,如果删除了最后一个元素,则为end()

您使用right.size() > 0保护此代码,只保证有一个项目。你有两个擦除操作。

您是否考察过在erase上执行right.end()的后果?