尝试在C ++中对字符串进行MergeSort,但无效

时间:2019-09-26 17:23:40

标签: string c++17 mergesort

尝试在c ++中对字符串进行MergeSort,但是出了点问题。

我正在使用vslang和clang,并且在编译时未显示任何错误/问题,但是在运行代码时,它只是停止并打开文件名“ char_traits.h”,然后打开show like this

然后我尝试在codepad.org上编译并显示

std::logic_error: basic_string::_S_construct NULL not valid
Aborted.
#include <iostream>
#include <limits>
using namespace std;

template <typename T> void merge(T *arr, int left, int mid, int right) {
  int leftLength = mid - left + 1;
  int rightLength = right - mid;
  T *L = new T[leftLength];
  T *R = new T[rightLength];

  for (int i = 0; i < leftLength; i++)
    L[i] = arr[left + i];
  for (int i = 0; i < rightLength; i++)
    R[i] = arr[mid + 1 + i];

  L[leftLength] = numeric_limits<T>::max();
  R[rightLength] = numeric_limits<T>::max();

  int leftIndex = 0, rightIndex = 0;
  for (int i = left; i <= right; i++) {
    if (L[leftIndex] <= R[rightIndex]) {
      arr[i] = L[leftIndex];
      leftIndex++;
    } else {
      arr[i] = R[rightIndex];
      rightIndex++;
    }
  }
}

template <typename T> void mergeSort(T *arr, int left, int right) {
  if (left < right) {
    int mid = (left + right) / 2;
    mergeSort(arr, left, mid);
    mergeSort(arr, mid + 1, right);
    merge(arr, left, mid, right);
  }
}

int main() {
  string a[3];
  a[0] = "abc";
  a[1] = "afd";
  a[2] = "fhe";
  mergeSort(a, 0, 2);
  for (int i = 0; i < 3; i++) {
    cout << a[i] << endl;
  }
  return 0;
}

我迷路了。谢谢!

0 个答案:

没有答案