Mergesort - std :: bad_alloc thrown while trying to assign a vector

Good afternoon, ladies and gentlemen. So, this is not my day for mistakes. Implementing Mergesort (out of place) in C ++, and I am having real problems with the code, not knowing why. The second-last line of the function mergeSort()assigns the result to merge()the vector of ints, result. This line (the actual distribution, not the function) is causing an error bad_alloc, and I have no idea why.

On the Internet, it is assumed that it bad_allocis mainly thrown out due to memory errors, but this cannot be the case the first time its caller is on a 500 ints vector, which should be next to too much memory anywhere (what is it like 2 kb on a 32 bit int?). I suppose I'm doing something stupid and wrong for C ++, but I don't know what. I tried calling what()for exception, but that just returns its name. The code:

vector<int> Sorting::mergeSort(vector<int> A) {

    // If the length of A is 0 or 1, it is sorted.
    if(A.size() < 2) return A;

    // Find the mid-point of the list.
    int midpoint = A.size() / 2;

    // Declare the left/right vectors.
    vector<int> left, right;

    // Declare the return vector.
    vector<int> result (A.size());

    for(int i = 0; i < midpoint; ++i) {
        left.push_back(A.at(i));
    }

    for(int i = midpoint; i < A.size(); ++i) {
        right.push_back(A.at(i));
    }

    left = mergeSort(left);
    right = mergeSort(right);
    result = merge(left, right);

    return result;

}


vector<int> merge(vector<int> left, vector<int> right) {

    vector<int> result;

    while(left.size() > 0 && right.size() > 0) {

        if(left.front() <= right.front()) {
            result.push_back(left.front());
            left.erase(left.begin());
        } else {
            result.push_back(right.front());
            right.erase(right.begin());
        }
    }

    if(left.size() > 0) {
        for(int i = 0; i < left.size(); ++i) {
            result.push_back(left.at(i));
        }
    } else {
        for(int i = 0; i < right.size(); ++i) {
            result.push_back(right.at(i));
        }
    }

}

If I re-write a function mergeto just take the link to resultand edit it during the function, it works fine, but I would like to keep the code as close as possible to the standard psuedo merge-sort code.

I appreciate any help, thanks.

+3
1

Merge vector<int> result .

+3

Source: https://habr.com/ru/post/1759778/


All Articles