【发布时间】:2018-05-08 21:41:00
【问题描述】:
我正在使用来自GeeksForGeeks 的代码,并且我想在大输入文件上对其进行测试,因此我对代码进行了一些修改以动态分配数组。
我知道我收到了这个错误:
在抛出 'std::bad_alloc 的实例后调用终止 什么():std::bad_alloc`
因为我内存不足,但我不知道读取大文件的正确方法,以供参考。
这是我正在使用的代码
#include<iostream>
#include<string.h>
#include<fstream>
#include <time.h>
#include <stdio.h>
using namespace std;
// A utility function to find maximum of two integers
int max(int a, int b)
{ return (a > b)? a : b; }
/* Returns length of longest common substring of X[0..m-1]
and Y[0..n-1] */
int LCSubStr(char *&X, char *&Y, int m, int n)
{
// Create a table to store lengths of longest common suffixes of
// substrings. Notethat LCSuff[i][j] contains length of longest
// common suffix of X[0..i-1] and Y[0..j-1]. The first row and
// first column entries have no logical meaning, they are used only
// for simplicity of program
clock_t t;
t=clock();
int** LCSuff = new int*[m+1];
for(int i = 0; i < m+1; ++i)
LCSuff[i] = new int[n+1];
int result = 0; // To store length of the longest common substring
/* Following steps build LCSuff[m+1][n+1] in bottom up fashion. */
for (int i=0; i<=m; i++)
{
for (int j=0; j<=n; j++)
{
if (i == 0 || j == 0)
LCSuff[i][j] = 0;
else if (X[i-1] == Y[j-1])
{
LCSuff[i][j] = LCSuff[i-1][j-1] + 1;
result = max(result, LCSuff[i][j]);
}
else LCSuff[i][j] = 0;
}
}
t = clock() - t;
printf("It took me %d clicks (%f seconds).\n",t,((float)t)/CLOCKS_PER_SEC);
cout<<"----------------------------"<<endl;
return result;
}
/* Driver program to test above function */
int main()
{
std::ifstream in("F1.txt");
std::string XS((std::istreambuf_iterator<char>(in)),
std::istreambuf_iterator<char>());
std::ifstream inn("F2.txt");
std::string YS((std::istreambuf_iterator<char>(inn)),
std::istreambuf_iterator<char>());
char *X=new char[XS.length()];
char *Y=new char[YS.length()];
XS.copy( X, XS.length() );
YS.copy( Y, YS.length() );
int m = strlen(X);
int n = strlen(Y);
cout << "Length of Longest Common Substring is "
<< LCSubStr(X, Y, m, n)<<endl;
return 0;
}
【问题讨论】:
-
使用内存映射文件。
-
不要使用 GeeksForGeeks 的代码似乎是最好的建议。
-
如果您使用的是字符串,请使用
std::string而不是手动分配空间。如果是二进制数据则std::vector<char>. -
@NathanOliver:
std::vector<uint8_t>将是二进制数据的更好选择,因为char可以是有符号或无符号或char。通常对于二进制数据,所有 8 位都是有效的。 -
@NathanOliver 我尝试使用向量,我仍然得到同样的错误