c++ - 递归生成组合并存储到向量时的 bad_alloc()
问题描述
概述:我正在尝试从具有特定起始字符的一组字符中生成组合,其中每个组合在一个范围内具有一定的长度。例如,如果我的字符集是 {A,B,C,D} 和起始前缀“A”,那么我的长度 1 到 3 的组合是:A、AA、AB、AC、AD、AAA、AAB、AAC、AAD ,....,添加。
问题:我递归地产生每个组合。问题是当我尝试将组合存储到一个向量中以获取长度范围为 1 到 8 的更大字符集(我显然明白这是许多组合)我得到一个 bad_alloc 核心转储错误。我的理解是,这意味着我的内存不足(可能是由于我的向量已满)。我想尝试将此向量分配给堆并保持全局。以下是我在尝试修改之前的当前代码:
#include <iostream>
#include <vector>
#include <string>
#include <time.h>
using namespace std;
#define SIZE_SET 15 // sizeof set below, set of characters to create permutations from
char set[] = {'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O'};
void ProducePerms(vector<string>&, string, const int, const int);
int main(){
// Timing program run time
clock_t t1, t2;
t1 = clock();
cout << "Starting time" << endl;
vector<string> perms; // Stores permutations
string start_prefix = "B"; // All permutations of lengths 1-8 begin with this prefix
int length = 8; // Maximum length of permutation
// Produce lengths 1-8 permutations starting with prefix
for(int l = 0; l < length; l++){
ProducePerms(perms, start_prefix, SIZE_SET, l);
}
// End run time
t2 = clock();
cout << "\nTime elapsed: " << (t2-t1)/(double)CLOCKS_PER_SEC << endl << endl;
return 0;
}
void ProducePerms(vector<string>& vec, string prefix, const int n, const int length){
if(length == 0){
vec.push_back(prefix);
}
else{
if(length == 1){
for(int j = 0; j < n; j++){
vec.push_back(prefix + set[j]);
}
}
else{
for(int i = 0; i < n; i++){
ProducePerms(vec, prefix + set[i], n, length - 1);
}
}
}
}
另外,如果有人对我如何适应使用 pthreads 有任何建议,那将很有帮助。我目前正在考虑创建 pthread 来计算一定长度的组合。
解决方案
推荐阅读
- windows - 深色主题更新导致 Eclipse 启动停止
- java - 如何更改 SQL Server 的默认时区
- docker - 如何 Codeception 和 Gitlab CI(持续集成)
- python - 更改 figsize 会导致输出图像为空
- java - 每天上午 12 点运行 Schulding 任务的问题 - Java
- swift - 如何使用 SwiftUI 将视图拉伸到其父框架?
- python - 将请求从 python 转换为节点 js
- python - 如何在 django 中解决“TypeError at /post/new/”
- sql-server - SSRS/SQL 中的双重拆分
- flutter - 如何为 futurebuilder 调用 setState