1
votes

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.

1
Since you can't assign to v, you can't pass it by reference either. Why are you taking a parameter by reference in the first place? - Igor Tandetnik
VS2017 says "cannot convert argument 1 from 'int [20]' to 'int *&" which is perhaps a little clearer. What I'd suggest is that you use C++ container classes like std::array instead 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. - Rook
@IgorTandetnik should write the code the Fusion function - Alberto
The fact that you're using C functions via a C++ namespace doesn't really matter. You're still not using any C++ containers. The containers are there to make your life easier. You should use them. - Rook
Neither Mergesort nor Fusion modify their first parameter, so again, there's no reason for them to take it by reference. Drop the ampersand, just int* v. - Igor Tandetnik

1 Answers

1
votes

I replaced *& with * in your Mergesort(int*&, int, int) to make it Mergesort(int*, int, int) and that worked for me.