Home > OS >  Recursive Merge Sort, wrong data type for argument?
Recursive Merge Sort, wrong data type for argument?

Time:11-09

I feel like ive properly solved the problem, but the program my school is using wants me to add to existing code. The types conflict, and i get this error:

main.cpp: In function ‘void mergeSort(std::vector<int>&, int, int)’:
main.cpp:21:25: error: cannot convert ‘std::vector<int>’ to ‘int*’ for argument ‘1’ to ‘void merge(int*, int, int, int)’
   merge(array, p, mid, r);
#include <vector>
using namespace std;

// Takes in an array that has two sorted subarrays,
//  from [p..q] and [q 1..r], and merges the array
void merge(int array[], int p, int q, int r) {
  // This code has been purposefully obfuscated,
  //  as you'll write it yourself in next challenge.
  int i, j, k; int n1 = q - p   1; int n2 =  r - q; int L[n1], R[n2]; for (i = 0; i < n1; i  ) L[i] = array[p   i]; for (j = 0; j < n2; j  ) R[j] = array[q   1  j]; i = 0;j = 0;k = p; while (i < n1 && j < n2){ if (L[i] <= R[j]) { array[k] = L[i]; i  ;} else { array[k] = R[j]; j  ; } k  ; } while (i < n1) { array[k] = L[i]; i  ; k  ; } while (j < n2) { array[k] = R[j]; j  ; k  ; }
}

// Takes in an array and recursively merge sorts it
void mergeSort(vector<int>& array, int p, int r) {
  if(p >= r)
  {
    return;
  }
  int mid = (p   r) / 2;
  mergeSort(array, p, mid);
  mergeSort(array, mid   1, r);
  merge(array, p, mid, r);
};

This is what is provided. I'm told to add the definition to mergeSort

I have not tested the code, so it could be wrong. This is not about how to solve Merge Sort, it is about the different types and get merge to accept it. Forgive me if this question is not formatted right, first time here.

Thanks in advance!

CodePudding user response:

To get the underlying int* in array, use the .data() metjhod:

void mergeSort(vector<int>& array, int p, int r) {
  //stuff
  merge(array.data(), p, mid, r);
};

The .data() method returns an int* representing the underlying buffer in which the elements of the vector are stored. This should remove the error.

  • Related