这是我的代码,用于在大型数组中查找频繁的数字。它可以正常工作500,000。
谁能帮助我,告诉我为什么它崩溃了n = 2,000,000?

我尝试将int更改为long或double,但是它崩溃了/不允许我进行编译。

#include <iostream>
#include <algorithm>
#include <cstdlib>
#include <ctime>

using namespace std;

int main() {

int n=500000;
int A[n];
clock_t begin, end; // this is used for measuring the running time
double elapsed_secs;
int ans;


for (int i=0; i<=0.1*(n-1); i++){
    A[i]=n-i;
}

for (int i=0.1*n; i<n; i++){
    A[i]=1;
}


/* Now we run the first algorithm, which is always correct.
 */

begin = clock(); // start couting the time
ans = almostUnanimousAlwaysCorrect(A, n);
end = clock(); // end counting the time
elapsed_secs = 1000*double(end - begin) / CLOCKS_PER_SEC;
cout << endl << "(1) The first algorithm (which is always correct) answers "<<endl;

if (ans==1) cout << "1 (correct)\n";
else  cout << "no frequent number (wrong) \n";

cout << "Time taken for the first algorithm is " << elapsed_secs << " milliseconds." << endl<<endl;


/* Now we run the second algorithm, which is NOT always correct.
   Note that the sorting function change how A looks. So, in principle,
   we should reset A. But let's not worry about that for now.
 */

begin = clock(); // start couting the time
ans = almostUnanimousRandom(A, n);


end = clock(); // end counting the time
elapsed_secs = 1000*double(end - begin) / CLOCKS_PER_SEC;
cout << endl << "(2) The second algorithm (which is NOT always correct) answers "<<endl;
if (ans==1) cout << "1 (correct)\n";
else  cout << "no frequent number (wrong) \n";

cout << "Time taken for the second algorithm is " << elapsed_secs << " milliseconds." << endl<<endl;


system("pause");


}

最佳答案

您的堆栈内存不足。而是在堆上分配它:

int n=500000;
int* A = new int[n];


然后当您完成后:

delete[] A;

关于c++ - 数组大小为200万的Frequent Number(工程为500k,但挂200万?),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16386636/

10-12 20:37