我正在尝试使用“插入排序”方法对数组的向量进行排序。但是我遇到了下面提到这两行的错误:
vec.insert(j , vec[i]);
vec.erase(i+1);完整代码:
#include<iostream>
#include<vector>
/*
I could do it recursively
*/
void ins_sort(std::vector<int> vec );
int main(){
std::vector<int> vec = {2 , 8 , 5 , 3 , 9 , 4};
ins_sort(vec);
}
void ins_sort(std::vector<int> vec ){
    for (int i = 1 ; i < vec.size() ; i++){
        if(vec[i] < vec[i-1]){ //look for a index which value is lower than vec[i], then move vec i to the index after that
            for (int j = 0 ; j <vec.size() ; j++){
                if (vec[i] < vec[j] ){
                    vec.insert(j , vec[i]);//inserting vec[i] into the right position
                    vec.erase(i+1); //erasing vec[i] which now is vec[i+1] after insertion
                    break; //ending the inner loop after finding the first greater value
                }
            }
        }
    }
}错误:

我检查了插入向量和从中删除的语法,但它看起来很好。我不确定为什么会出现这个错误。
更新:已将"vec.begin()“添加到索引地址,如下所示:
#include<iostream>
#include<vector>
/*
I could do it recursively
*/
void ins_sort(std::vector<int> vec );
int main(){
std::vector<int> vec = {2 , 8 , 5 , 3 , 9 , 4};
ins_sort(vec);
}
void ins_sort(std::vector<int> vec ){
    for (int i = 1 ; i < vec.size() ; i++){
        if(vec[i] < vec[i-1]){ //look for a index which value is lower than vec[i], then move vec i to the index after that
            for (int j = 0 ; j <vec.size() ; j++){
                if (vec[i] < vec[j] ){
                    vec.insert(vec.begin() + j , vec[i]);//inserting vec[i] into the right position
                    vec.erase(vec.begin() + i + 1); //erasing vec[i] which now is vec[i+1] after insertion
                    break; //ending the inner loop after finding the first greater value
                }
            }
        }
    
    }
  for (int i = 0 ; i < vec.size() ; i++){
    std::cout<<vec[i];  
}
}发布于 2021-04-24 22:24:28
一种快速而肮脏的解决方法:
vec.insert(vec.begin() + j , vec[i]);//inserting vec[i] into the right position
vec.erase(vec.begin() + i + 1); //erasing vec[i] which now is vec[i+1] after insertion另外,请从ins_sort函数返回排序后的向量
https://stackoverflow.com/questions/67243555
复制相似问题