I'm trying to implement the mergesort algorithm and I don't understand this error:
error: invalid initialization of non-const reference of type ‘int*&’ from an rvalue of type ‘int*’
Mergesort (v, 0, TAM - 1);
___________________^note: initializing argument 1 of ‘void Mergesort(int*&, int, int)’
void Mergesort (int *&v, int ini, int fin);
^
Relevant parts of my code:
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
void Mergesort (int *&v, int ini, int fin);
void Fusion (int *&v, int ini, int centro, int fin);
int main(){
const int TAM = 20;
int v[TAM];
time_t t;
srand ((int) time(&t));
const int MIN = -100, MAX=100, NUM_VALORES = MAX-MIN+1;
for (int i = 0; i < TAM; i++){
v[i] = (rand() % NUM_VALORES) + MIN;
}
...
Mergesort (v, 0, TAM - 1);
...
return 0;
}
void Mergesort (int *&v, int ini, int fin){
int centro;
if (ini < fin){
centro = (ini + fin) / 2;
Mergesort (v, ini, centro);
Mergesort (v, centro + 1, fin);
Fusion (v, ini, centro, fin);
}
}
void Fusion (int *&v, int ini, int centro, int fin){
int aux[fin - ini + 1];
int h, i, j, k;
h = ini;
i = ini;
j = centro + 1;
while ( (i <= centro) && (j <= fin) ){
if (v[i] <= v[j]){
aux[h] = v[i];
i++;
}else{
aux[h] = v[j];
j++;
}
h++;
}
if (i > centro){
for (k = j; k <= fin; k++){
aux[h] = v[k];
h++;
}
}else{
for (k = i; k <= centro; k++){
aux[h] = v[k];
h++;
}
}
for (k = ini; k <= fin; k++){
v[k] = aux[k];
}
}
I am aware there are questions in this site about similar errors but I couldn't solve my problem.
v, you can't pass it by reference either. Why are you taking a parameter by reference in the first place? - Igor Tandetnikstd::arrayinstead of c-style arrays as you're doing. If you're going to write C++, you may as well use the facilities it gives you. - RookMergesortnorFusionmodify their first parameter, so again, there's no reason for them to take it by reference. Drop the ampersand, justint* v. - Igor Tandetnik