0

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

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

1 回答 1

1

你的right.erase(right.erase(right.begin()));代码看起来很狡猾。该erase函数返回一个迭代器,指向被删除元素的后继元素,end()如果你删除了最后一个元素。

您正在保护这个代码 right.size() > 0,它只保证有一个项目。您有两个擦除操作。

你有没有研究过这样做的erase后果right.end()

于 2012-04-10T01:59:57.497 回答