-1
#include <iostream>
#include<vector>
#include<algorithm>
using namespace std;

void insSort(vector<int> arr)
{
    vector<int>::iterator i;
    for (i = arr.begin(); i != arr.end(); i++)
    {
        //first
                cout << *i<<endl;
    }
    sort(arr.begin(), arr.end());
    cout << "调用排序函数成功"<<endl;
    for (i = arr.begin(); i != arr.end(); i++)
    {
        //second
                cout << *i << endl;
    }
}
int main()
{
    int n;
    cin >> n;
    cout << "n=" << n;
    vector<int> arr(n);
    
    for(int i=0;i<n;i++)
        cin >> arr[i];

    insSort(arr);
    vector<int>::iterator i;

    for (i=arr.begin(); i != arr.end(); i++)
    {
        //third
                cout << *i;
    }

    return 0;
}


calling Funtion insSort() int main funtion,first print is before sorting,second print is after sort,and for third print, I think it is after print,but it has the same result with first,I can not understand.Could you tell me what is wrong with it. Thank you.

Michel G
  • 116
  • 6
pipi
  • 1

1 Answers1

2

The problem is you are passing arr by value instead of by reference. You're sorting a copy of arr, rather than the original array. Change

void insSort(vector<int> arr)

to

void insSort(vector<int>& arr)

and the code will work

weeb
  • 1,939
  • 4
  • 18
  • 29