Home > OS >  Unhandled exception : An invalid parameter was passed to a function that considers invalid parameter
Unhandled exception : An invalid parameter was passed to a function that considers invalid parameter

Time:09-27

I am working on an insertion sort with vector in C .However, I got an problem when I want to print the vector for the first 10 element.

void insertion_sort(vector<int> &data, int n)
{
    int temp;
    int i;
    int j;

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

int main()
{
    int size;
    cin >> size;
    vector<int> list;
    for (int i = 0; i < size; i  ) {
        list.push_back(rand());
    }
  
    insertion_sort(list, size);
    cout << "first 10 value in list is:";
    for (int j = 0; j < 10; j  ) { 
        vector<int> arr(list.begin(), list.begin() j);
        cout << arr.front() << ", "; 
    }

}

The input of size is 1000. But, an error occurred with : Unhandled exception at 0x7927F2F6 (ucrtbased.dll): An invalid parameter was passed to a function that considers invalid parameters fatal. at the line of vector<int> arr(list.begin(), list.begin() j); How can I fix this issue?

CodePudding user response:

I fixed the problem with size < 10 (correct count being displayed and crash), language of message, printing out the values (main issue), use new line instead of ", " after last value, and also reduced scope of variables, return from main:

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

void insertion_sort(vector<int> &data, int n) {
    for (int i = 1, j; i < n; i  ) {
        int temp = data[i];
        j = i - 1;
        while (j >= 0 && data[j] > temp) {
            data[j   1] = data[j];
            --j;
        }
        data[j   1] = temp;
    }
}

int main() {
    int size;
    cin >> size;
    vector<int> list;
    for (int i = 0; i < size; i  ) {
        list.push_back(rand());
    }
  
    int size2 = size < 10 ? size : 10;
    insertion_sort(list, size);
    cout << "first " << size2 << " value(s) in list: ";
    for (int j = 0; j < size2; j  ) { 
        cout << list[j];
        if(j   1 < size2) {
             cout << ", ";
        }
    }
    cout << "\n";
    return 0;
}

Example output with input 3 and 20:

first 3 value(s) in list: 846930886, 1681692777, 1804289383
first 10 value(s) in list: 304089172, 424238335, 596516649, 719885386, 783368690, 846930886, 1025202362, 1102520059, 1189641421, 1303455736

Perhaps you should validate that size > 0.

  • Related