向量笛卡尔积_当元素数大于1000时,如何生成向量的笛卡尔积?

我有1,2,…,n个向量。每个向量都有超过10000个元素,我必须得到这些向量的笛卡尔积。我有一个代码,正在工作,但只有1000个元素和4个向量下。

我想将笛卡尔积写入一个文件,但如果输出文件大于1GB,我得到的是:“在抛出'std::bad戡alloc'what():std::bad戡alloc'实例后终止调用”。

我的主要问题是,如何修复这个内存分配错误?

下面是我的代码的一段可运行代码:

#include

#include

#include

#include

#include

#include

using namespace std;

vector makeVectorByRange(double min, double max, double step){

vector out = {};

for( ; min <= max; min+=step){

out.push_back(min);

}

return out;

}

void cart_product_solve_and_write_to_file (const vector>& inpV) {

vector> out = {{}};

std::ofstream outputFile;

std::fixed;

for (auto& u : inpV) {

vector> r;

r.clear();

for (auto& x : out) {

//make/open file, append

outputFile.open ("out.csv", std::ofstream::out | std::ofstream::app);

outputFile.precision(8);

for (auto y : u) {

r.push_back(x);

r.back().push_back(y);

if( r.back().size() == inpV.size() ){

// write the input parameters of griewank to file

for(double asd : r.back()){

outputFile << asd << ";";

}

outputFile << "; \n";

outputFile << std::flush;

r.back().clear();

}

}

//close file

outputFile.close();

}

out.swap(r);

}

}

// Pure cartesian product. This function returns the cartesian product as a vector, but if the input vectors are too big, it has an error

/*

vector < vector > cartesian_product (const vector< vector >& inpV) {

vector< vector > out = {{}};

for (auto& u : inpV) {

vector< vector > r;

for (auto& x : out) {

for (auto y : u) {

r.push_back(x);

r.back().push_back(y);

}

}

out.swap(r);

}

return out;

}

*/

int main(){

clock_t tStart = clock();

// it works

// const vector > test ={ {0,1,2,3,4}, {5,6,7}, {8,9,10,11,12,13} };

// vector > cart_prod = cartesian_product(test);

vector > test = {};

test.push_back( makeVectorByRange( 0, 0.5, 0.001) );

test.push_back( makeVectorByRange( 0, 0.5, 0.001) );

test.push_back( makeVectorByRange( 0, 0.5, 0.001) );

cart_product_solve_and_write_to_file(test);

printf("Time taken: %.6fs\n", (double)(clock() - tStart)/CLOCKS_PER_SEC);

return 0;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值