-2

I have two functions that I am using to attempt to perform a merge sort. Unfortunately, it claims that my call to merge does not match any existing function definitions- which has me dumbfounded since it appears to match perfectly.

// Merge Sort:
vector<int> MergeSort(vector<int> &x) {
  int n = x.size();
  if (n <= 1) {
    return x;
  }
  size_t const half = x.size() / 2;
  vector<int> u(x.begin(), x.begin() + half);
  vector<int> v(x.begin() + half, x.end());
  vector<int> i = MergeSort(u);
  vector<int> j = MergeSort(v);
  vector<int> m = merge(i, j); // no matching function for call to 'merge'
  return m;
}
// Merge vector
vector<int> merge(vector<int> &x, vector<int> &y) {
  vector<int> t;
  while (!x.empty() || !y.empty()) {
    if (x.back() > y.back()) {
      t.push_back(y.back());
      y.pop_back();
    } else {
      t.push_back(x.back());
      x.pop_back();
    }
    if (!x.empty()) {
      t.push_back(x.back());
      x.pop_back();
    } else {
      t.push_back(y.back());
      y.pop_back();
    }
  }
  return t;
}

I have tried a bunch of silly things like changing the order of definitions and even testing this with different variable types but run into the same issue despite my efforts.

I've been messing with this for over an hour now and am completely stuck. I seriously hope I am not overlooking something obvious. Any help would be greatly appreciated!

Grant
  • 1
  • 1
  • 1
    You need to add a declaration of merge before you call it. – pm100 Dec 06 '22 at 22:51
  • 2
    The compiler reads from top to bottom just like you. When it reaches `merge` it doesn't know what it is, because it hasn't seen it before. @pm100 can you find a dupe? I am struggling – Fantastic Mr Fox Dec 06 '22 at 22:53
  • Just place `vector merge(vector &x, vector &y);` before the `MergeSort()` definition. – πάντα ῥεῖ Dec 06 '22 at 22:54
  • @πάνταῥεῖ to go along with that, [here is a live example](http://coliru.stacked-crooked.com/a/b4d313f213f9f780). – Fantastic Mr Fox Dec 06 '22 at 22:55
  • 1
    Me, I'd move the whole function. Sucks when someone changes the declaration and forgets to make the same change to the definition. – user4581301 Dec 06 '22 at 23:01
  • Does this answer your question? [What are forward declarations in C++?](https://stackoverflow.com/questions/4757565/what-are-forward-declarations-in-c) – n0rd Dec 07 '22 at 00:32

1 Answers1

0

Found the solution. In the post I mentioned that I had already tried switching the function declaration order but had no success. What I discovered was that by recursively calling MergeSort() in the return line (which is what I had done originally), I got still got the same compiler error, regardless of function declaration order. This of course mislead me to believe that the order did not matter since it was a combinative issue. Thus, the final solution was changing the function order to be proper and breaking up the single line format.

Grant
  • 1
  • 1