【发布时间】:2021-04-24 13:56:08
【问题描述】:
我正在尝试使用“插入排序”方法对数组向量进行排序。 但我面临底部显示的错误,指的是这两行:
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];
}
}
【问题讨论】:
-
你应该了解迭代器
-
@MatG 请多解释
-
int ins_sort(std::vector<int> vec ){请注意,您通过值传递vec,这意味着调用函数将看不到此函数内部的任何更改。 -
insert 为第一个参数而不是索引采用迭代器:https://en.cppreference.com/w/cpp/container/vector/insert 此链接底部的示例代码可以帮助您解决此问题。
标签: c++ error-handling