merge sort algorithm: std::out_of_range

  algorithm, c++, dsa, mergesort

I am currently making a merge sort algorithm but when i run the code i get an error says "terminate called after throwing an instance of ‘std::out_of_range". This is my code.

template<typename T>
void merge(std::vector<T> &vec, int l, int m, int r){
    int i = l;
    int j = m + 1;
    int k = l;
    
    //CREATE TEMPORARY MEMORY
    int temp[vec.size()];

    while(vec.at(i) <= m && j <= r){
        if(vec.at(i) <= vec.at(j)){
            temp[k] = vec.at(i);
            i++;
            k++;
        }else{
            temp[k] = vec.at(j);
            j++;
            k++;
        }
    }
    while (i <= m){ //first half: Copy the remaining elements of first half, if there are any
        temp[k] = vec.at(i);
        i++;
        k++;
    }
    while (j <= r){ //second half: Copy the remaining elements of second half, if there are any 
        temp[k] = vec.at(j);
        j++;
        k++;
    }
    for(size_t p = 1; p <= r; p++){ //copy temp array to original array
        vec.at(p) = temp[k];
    }
}

Merge Sort Function

template<typename T>
void mergeSort(std::vector<T> &vec, int l, int r){
    if(l < r){ 
        int m = (l + r) / 2; //find midpoint
        mergeSort(vec, l, m); //first half
        mergeSort(vec, m + 1, r); //second half
        merge(vec, l, m, r); // merge
    }
}

Source: Windows Questions C++

LEAVE A COMMENT