我不理解我在C++的归并排序中遇到的错误。

huangapple go评论94阅读模式
英文:

I do not understand the error I am getting in Merge sort in C++

问题

I am learning the Merge sorting technique and wrote this code by following a tutorial. However, I am getting an error here. I would like to understand the mistakes, I am doing here.
使用在线编译器时,遇到分段错误,而在本地,则发现操作符不匹配的错误。

英文:

I am learning the Merge sorting technique and wrote this code by following a tutorial. However, I am getting an error here. I would like to understand the mistakes, I am doing here.
On using online compiler I encountered Segmentation error, while locally, error like operator not matching is found.

  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. void merge(vector<int> &arr, int low, int mid, int high){
  4. vector<int> temp;
  5. int left=low;`enter code here`
  6. int right=mid+1;
  7. while (left<=mid && right<=high)
  8. {
  9. if(arr[left]<=arr[right]){
  10. temp.push_back(arr[left]);
  11. left++;
  12. }
  13. else{
  14. temp.push_back(arr[right]);
  15. right++;
  16. }
  17. }
  18. while(left<=mid){
  19. temp.push_back(arr[left]);
  20. left++;
  21. }
  22. while(right<=high){
  23. temp.push_back(arr[right]);
  24. right++;
  25. }
  26. for(int i=low;i<=high;i++){
  27. arr[i]=temp[i-low];
  28. }
  29. }
  30. void mS(vector<int> &arr, int low, int high){
  31. if(low>=high) return;
  32. int mid=(low+high)/2;
  33. mS(arr, low, mid);
  34. mS(arr, mid+1, high);
  35. merge(arr, low, mid, high);
  36. }
  37. void mergeSort(vector<int> &arr, int n){
  38. mS(arr, 0, n-1);
  39. }
  40. int main()
  41. {
  42. int n;
  43. cin >> n;
  44. vector<int> arr;
  45. for (int i = 0; i < n; i++)
  46. {
  47. cin >> arr[i];
  48. }
  49. mergeSort(arr, n);
  50. for (int i = 0; i < n; i++)
  51. {
  52. cout << arr[i] << " ";
  53. }
  54. }

答案1

得分: 2

vector<int> arr; 是一个空的 vectorcin >> arr[i]; 写入了一个不存在的数组。

vector<int> arr; 改为 vector<int> arr(n);,以初始化具有 n 个元素的 vector

之后程序似乎在运行:https://godbolt.org/z/szvzeoxbW

英文:

vector&lt;int&gt; arr; is an empty vector. cin &gt;&gt; arr[i]; writes to a non existing array.

Change vector&lt;int&gt; arr; to vector&lt;int&gt; arr(n); to initialize the vector with n elements.

After that it looks like the program is running: https://godbolt.org/z/szvzeoxbW

huangapple
  • 本文由 发表于 2023年5月26日 15:44:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/76338686.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定