【问题标题】:How do I call the InsertionSort method here?如何在这里调用 InsertionSort 方法?
【发布时间】:2016-08-11 11:58:21
【问题描述】:

我有以下代码。该方法应该可以工作,但是我无法将向量传递给函数。我四处搜索,发现向量可以作为“引用”或“值”传递,我都试过了,但它们似乎不起作用。我是否错误地调用了该方法或以错误的方式传递了向量?无论哪种方式,我该怎么做才能解决这个问题?谢谢! :)

//insertion sort method

#include <iostream> 
#include <vector>
using namespace std; 

void insertionSort(int arr[], int n){ 
for(int i = 0; i < n; i++){

int temp = arr[i]; // element adjacent to left sorted array 
int j = i - 1; 

while(temp > arr[j] && j != 0){
    arr[j] = arr[j - 1]; 
    j--; 
}
arr[j] = temp; 
}
}

int main(){ 
int n, temp; 
cin >> n; 
vector <int> arr; 

for(int i = 0; i < n; i++){
cin >> temp; 
arr.push_back(temp); 
}

insertionSort(arr, n); 

for(int i = 0; i < n; i++)
cout << arr[i] << " "; 

return 0;
}

【问题讨论】:

  • 将你的函数定义头改为void insertSort(vector &arr, int n),整数数组和整数向量是不同的数据类型,你不能将向量传递给期望整数数组的函数。

标签: c++ vector methods stl


【解决方案1】:

insertionSort(int arr[], int n) 方法的第一个参数错误。 您还错误地处理了 arr。在第一次迭代中,int j = 0 - 1 = -1;这是意外/超出范围。

请试试这个:

void insertionSort(vector <int> &arr, int n){

    int i, j, temp;
    for (i = 1; i < n; i++)
    {
        temp = arr[i];
        j = i - 1;
        while ((j >= 0) && (temp<arr[j]))
        {
            arr[j + 1] = arr[j];
            j = j - 1;
        }
        arr[j + 1] = temp;
    }
}

谢谢!!!

【讨论】:

  • 非常感谢 Monirul :)
猜你喜欢
  • 1970-01-01
  • 2023-03-04
  • 1970-01-01
  • 2013-03-18
  • 1970-01-01
  • 2022-01-08
  • 2021-01-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多