【问题标题】:c++: Reason of "No instance of overloaded function"c++:“没有重载函数实例”的原因
【发布时间】: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&lt;int&gt; vec ){ 请注意,您通过值传递vec,这意味着调用函数将看不到此函数内部的任何更改。
  • insert 为第一个参数而不是索引采用迭代器:https://en.cppreference.com/w/cpp/container/vector/insert 此链接底部的示例代码可以帮助您解决此问题。

标签: c++ error-handling


【解决方案1】:

快速而肮脏的解决方法:

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函数返回排序后的向量

【讨论】:

  • 为什么我需要将 vec.begin() 添加到索引的开头?我知道它是一个指向向量容器第一个元素的迭代器。但是为什么“i”和“j”本身还不够呢?是因为向量是动态的吗?
  • 更新:此链接有帮助:stackoverflow.com/questions/30510814/…
  • 嗨,@Max。最好避免使用 insertdelete 方法,因为它们会导致向量的重新分配。顺序复制元素以保持向量的完整性可能会更好。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-16
  • 2019-08-11
  • 1970-01-01
  • 2014-04-17
  • 2021-10-13
  • 1970-01-01
相关资源
最近更新 更多