在抛出 'std::bad_alloc' 的实例后调用终止 what(): std::bad_alloc 中止
terminate called after throwing an instance of 'std::bad_alloc' what(): std::bad_alloc Aborted
我的程序中出现了bad_alloc
异常。
约束条件如下:
- 1 <= T <= 10
- 每个字符串的长度不超过100000,且只包含小写字符。
有了这些限制,我无法弄清楚为什么我的程序得到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;
}
因为你在这里所做的:
for (size_t i = 0; i < N; i++)
suffixes[i] = s.substr(i);
是:创建长度为0,1,2,…的N
子字符串。N这些将要消耗的内存总量是:1 + 2 + 3 + ... + N
字节。有了老高斯,你会发现前N
个数的和是:N * (N + 1) / 2
现在,如果您设置N = 100,000,这将导致大约5GB的内存消耗-这比最大值要大。你的程序通常有2GB的地址空间,除非你在64位系统上运行它。
编辑:我不知道你想解决什么问题,但你的实现似乎很奇怪:
你从来没有使用过计算的后缀:你使用的SuffixArray
的唯一函数是lcp
,它没有引用存储的suffixes
向量。那么你首先需要它们做什么呢?
相关文章:
- 使用std::multimap迭代器创建std::list
- C++中std::resize(n)和std::shrink_to_fit之间的区别
- 来自 std::list 的迭代器 .end() 按预期返回"0xcdcdcdcdcdcdcdcd"但 .begin()
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 如何导出包含具有"std::unique_ptr"值的"std::map"属性的
- 从持续时间构造std::chrono::system_clock::time_point
- std::具有相同基类的类的变体
- std::向量与传递值的动态数组
- 使用std::vector的OpenCL矩阵乘法
- std::map<struct,struct>::find 找不到匹配项,但是如果我循环通过 begin() 到 end(),我在那里看到匹配项
- std::condition_variable::wait()如何评估给定的谓词
- 如何获取std::result_of函数的返回类型
- std::原子加载和存储都需要吗
- 将对象移动到std::shared_ptr
- 获取错误:在抛出"std::bad::alloc"的实例后终止调用 what(): std::bad_alloc
- "std::vector"在调整大小时引发"bad allocation"异常
- 成员函数 bad() 的 std::ftsream 用于检查
- 正在使用std::string而不是char*bad
- 在抛出 'std::bad _alloc' 的实例后调用终止 what(): std::bad_alloc 在 c++ 中
- What is Scala for: getline(), std::cin.eof(), std::cin.bad()