我一直在我的代碼中得到一個未處理的異常,它讓我難住。C++大型矢量/陣列未處理異常
我相信這是我的變量聲明的方式。
基本上我試圖創建3個數組,M行,N列隨機變量。 如果我設置我的N = 1,000和M = 10,000,不是問題。 如果我然後改變M = 100,000,我得到一個未處理的異常內存分配錯誤。
有人可以幫我理解爲什麼會發生這種情況。
部分代碼寫在VS2010上。我現在已經轉向VS2013,所以任何關於使用新功能的額外建議也將被讚賞。 歡呼聲,雙打的
#include <cmath>
#include <iostream>
#include <random>
#include <vector>
#include <ctime>
#include <ratio>
#include <chrono>
int main()
{
using namespace std::chrono;
steady_clock::time_point Start_Time = steady_clock::now();
unsigned int N; // Number of time Steps in a simulation
unsigned long int M; // Number of simulations (paths)
N = 1000;
M = 10000;
// Random Number generation setup
double RANDOM;
srand((unsigned int)time(NULL)); // Generator loop reset
std::default_random_engine generator(rand()); // Seed with RAND()
std::normal_distribution<double> distribution(0.0, 1.0); // Mean = 0.0, Variance = 1.0 ie Normal
std::vector<std::vector<double>> RandomVar_A(M, std::vector<double>(N)); // dw
std::vector<std::vector<double>> RandomVar_B(M, std::vector<double>(N)); // uncorrelated dz
std::vector<std::vector<double>> RandomVar_C(M, std::vector<double>(N)); // dz
// Generate random variables for dw
for (unsigned long int i = 0; i < M; i++)
{
for (unsigned int j = 0; j < N; j++)
{
RANDOM = distribution(generator);
RandomVar_A[i][j] = RANDOM;
}
}
// Generate random variables for uncorrelated dz
for (unsigned long int i = 0; i < M; i++)
{
for (unsigned int j = 0; j < N; j++)
{
RANDOM = distribution(generator);
RandomVar_B[i][j] = RANDOM;
}
}
// Generate random variables for dz
for (unsigned long int i = 0; i < M; i++)
{
for (unsigned int j = 0; j < N; j++)
{
RANDOM = distribution(generator);
RandomVar_C[i][j] = RANDOM;
}
}
steady_clock::time_point End_Time = steady_clock::now();
duration<double> time_span = duration_cast<duration<double>>(End_Time - Start_Time);
//Clear Matricies
RandomVar_A.clear();
RandomVar_B.clear();
RandomVar_C.clear();
std::cout << std::endl;
std::cout << "its done";
std::cout << std::endl << std::endl;
std::cout << "Time taken : " << time_span.count() << " Seconds" << std::endl << std::endl;
std::cout << "End Of Program" << std::endl << std::endl;
system("pause");
return 0;
}
// *************** END OF PROGRAM ***************
你可以使用調試器,並準確地告訴你哪一行你得到一個未處理的異常?這聽起來像是一個內存分配問題。你可能沒有足夠的空閒內存... –
你的向量將使用'M * N * sizeof(double)'字節。如果你將'M'設置爲'100000',將'N'設置爲'1000',那麼你的每個向量將近800兆字節。你有* 2.4GB的可用內存嗎? –