首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >c++:没有重载函数实例的原因

c++:没有重载函数实例的原因
EN

Stack Overflow用户
提问于 2021-04-24 21:56:09
回答 1查看 104关注 0票数 0

我正在尝试使用“插入排序”方法对数组的向量进行排序。但是我遇到了下面提到这两行的错误:

代码语言:javascript
运行
复制
vec.insert(j , vec[i]);

vec.erase(i+1);

完整代码:

代码语言:javascript
运行
复制
#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()“添加到索引地址,如下所示:

代码语言:javascript
运行
复制
#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];  
}
}
EN

Stack Overflow用户

回答已采纳

发布于 2021-04-24 22:24:28

一种快速而肮脏的解决方法:

代码语言:javascript
运行
复制
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函数返回排序后的向量

票数 1
EN
查看全部 1 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67243555

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档