使用.erase(C )的逻辑错误

Logic error using .erase (C++)

本文关键字:错误 erase 使用      更新时间:2023-10-16

,所以我的程序只是读取数字的输入,并按顺序列出它们。如输出所示。没有使用算法库,我对其进行了排序并摆脱了重复的数据。但是,如果重复数据值,则未打印向量的最后值。我是否错误地使用.erase?

void remove_repeated(int size, vector<int>& num_vec){
    for(int i = 0; i < num_vec.size(); i++){
        if(num_vec[i]==num_vec[i+1]){
            num_vec.erase((num_vec.begin()+i));
        }   
    }
}

输出没有重复值时:

                 **Welcome to the HW Reading Program**
 Please, enter your HW:1-10
 Do Problems: 1, 2, 3, 4, 5, 6, 7, 8, 9,and 10

重复值时输出:

                 **Welcome to the HW Reading Program**
 Please, enter your HW: 1-10,1-3
 Do Problems: 1, 2, 3, 4, 5, 6, 7, 8,and 9

从向量删除索引i的元素后,下一个元素是index i,而不是index i+1。另外,与i+1相比,您必须注意不要脱离界限,即您的循环必须看起来像这样:

for(int i = 0; i < num_vec.size()-1;){
    if(num_vec[i]==num_vec[i+1]){
        num_vec.erase((num_vec.begin()+i));
    } else {
        i++;
    }
}

您还应该考虑使用标准库所提供的内容。set仅包含唯一元素,或者您可以使用erase unique(例如,请参阅此处有关更多详细信息)。