几天前我曾提出过这个问题,但并没有解决我的问题。我无法在Visual Studio中增加堆栈大小,我正在使用递归方法,输入较大时会导致堆栈溢出。我不能使用向量或其他东西。我需要的是在c++,Visual Studio中增加堆栈大小。
P.S. 我已经从Visual Studio配置中增加了堆栈保留大小,但它也没有解决我的问题。
void sorting:: MergeSort(int *theArray, int n) {
mergesort(theArray, 0, n - 1);
}
void sorting::mergesort(int *theArray, int first, int last) {
if (first < last) {
int mid = (first + last) / 2; // index of midpoint
mergesort(theArray, first, mid);
mergesort(theArray, mid + 1, last);
// merge the two halves
merge(theArray, first, mid, last);
}
} // end mergesort
void sorting::merge(int* theArray, int first, int mid, int last) {
const int max_size = 500000;
int tempArray[max_size];
int first1 = first; // beginning of first subarray
int last1 = mid; // end of first subarray
int first2 = mid + 1; // beginning of second subarray
int last2 = last; // end of second subarray
int index = first1; // next available location in tempArray
for (; (first1 <= last1) && (first2 <= last2); ++index) {
if (theArray[first1] < theArray[first2]) {
tempArray[index] = theArray[first1];
++first1;
}
else {
tempArray[index] = theArray[first2];
++first2;
}
}
// finish off the first subarray, if necessary
for (; first1 <= last1; ++first1, ++index)
tempArray[index] = theArray[first1];
// finish off the second subarray, if necessary
for (; first2 <= last2; ++first2, ++index)
tempArray[index] = theArray[first2];
// copy the result back into the original array
for (index = first; index <= last; ++index)
theArray[index] = tempArray[index];
delete[] tempArray;
} // end merge
我的主要功能。
#include <iostream>
#include <ctime>
#include "sorting.h"
using namespace std;
int main()
{
sorting sort;
int size = 500000;
int *myArr=new int[size];
for (int i = 0; i < size; i++) {
myArr[i] = rand() % size;
}
cout << clock()<<" ";
sort.MergeSort(myArr,size);
cout<<clock();
cin.get();
}
delete temparray;
?希望不是书的作者。承认吧,这段代码是错的。 - user4581301int* tempArray = new int [max_size];
替换int tempArray[max_size];
。你的delete
未定义,令人惊讶的是你没每次都崩溃。 - molbdniloconst
。使用了rand
,这是一个极其糟糕的生成器——改用random
工具库。使用模数获取分布——不要这样做,你会引入偏向。还有更多问题……这段代码存在许多问题之一就是栈溢出。 - Jesper Juhl