[英]terminate called after throwing an instance of 'std::bad_alloc' what(): std::bad_alloc Aborted
I am getting a bad_alloc
exception in my program. 我的程序中出现了bad_alloc
异常。
These are the constraints: 这些是约束:
With those constraints, I am unable to figure out why my program is getting bad_alloc
. 有了这些限制,我无法弄清楚为什么我的程序变得bad_alloc
。
#include <string>
#include <algorithm>
#include <iostream>
#include <vector>
class SuffixArray {
std::vector<std::string> suffixes;
size_t N;
public:
SuffixArray(std::string& s) {
N = s.length();
suffixes.resize(N);
for (size_t i = 0; i < N; i++)
suffixes[i] = s.substr(i);
std::sort(suffixes.begin() , suffixes.end());
}
~SuffixArray() {
}
size_t lcp(std::string& s, std::string& t) {
size_t N = std::min(s.length(), t.length());
for (size_t i = 0; i < N; i++)
if (s[i] != t[i])
return i;
return N;
}
};
int main ( int argc, char **argv) {
int T;
std::cin >> T;
std::vector<size_t> results;
for ( int i = 0; i < T; i++) {
std::string str;
std::cin >> str;
SuffixArray sa(str);
size_t sol = 0;
for ( std::string::iterator it = str.begin(); it != str.end(); ++it) {
std::string target = std::string(it, str.end());
sol += sa.lcp(str, target);
}
results.push_back(sol);
}
for ( std::vector<size_t>::iterator it = results.begin(); it != results.end(); ++it)
std::cout << *it << std::endl;
results.clear();
return 0;
}
Because what you do here: 因为你在这里做什么:
for (size_t i = 0; i < N; i++)
suffixes[i] = s.substr(i);
is: Create N
sub strings of lengths 0, 1, 2, ..., N The total amount of memory these are going to consume is: 1 + 2 + 3 + ... + N
bytes. 是:创建长度为0,1,2,...,N的N
个子字符串这些消耗的内存总量为: 1 + 2 + 3 + ... + N
个字节。 Having good old Gauss at your hand you will find that the sum of the first N
numbers is: N * (N + 1) / 2
有了好老高斯,你会发现前N
个数的总和是: N * (N + 1) / 2
Now if you set N = 100,000 this results in about 5GB of memory consumption - which is larger than the max. 现在,如果设置N = 100,000,则会导致大约5GB的内存消耗 - 大于最大值。 2GB address space your program usually has unless you run it on a 64bit system. 除非您在64位系统上运行它,否则程序通常具有2GB的地址空间。
Edit : I don't know what the problem is you are trying to solve however your implementation seems strange: 编辑 :我不知道你试图解决的问题是什么,但你的实现看起来很奇怪:
You never ever use the computed suffixes: The only function of SuffixArray
you are using is lcp
which makes no reference to the stored suffixes
vector. 你从来没有使用计算后缀:唯一的功能SuffixArray
您使用的是lcp
,这使得没有提及存储suffixes
载体。 So what you need them for in the first place? 那么你首先需要它们呢?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.