I have (sort of) learned c++ by myself for physics purposes, so I apologize if this is an easy question. I've tried to find the answer by myself using Google, but I didn't find anything useful (probably because I wasn't sure what kind of search words to use).
For my c++ program, I have to declare 100 (or more) variables like this:
vector< vector<double> > pol1_t1_matrix(SPACE_pol, vector<double>(2));
vector< vector<double> > pol1_t2_matrix(SPACE_pol, vector<double>(2));
vector< vector<double> > pol1_t3_matrix(SPACE_pol, vector<double>(2));
vector< vector<double> > pol1_t4_matrix(SPACE_pol, vector<double>(2));
vector< vector<double> > pol1_t5_matrix(SPACE_pol, vector<double>(2));
vector< vector<double> > pol1_t6_matrix(SPACE_pol, vector<double>(2));
vector< vector<double> > pol1_t7_matrix(SPACE_pol, vector<double>(2));
vector< vector<double> > pol1_t8_matrix(SPACE_pol, vector<double>(2));
vector< vector<double> > pol1_t9_matrix(SPACE_pol, vector<double>(2));
vector< vector<double> > pol1_t10_matrix(SPACE_pol, vector<double>(2));
etc.;
I also use these to write files as follows:
ofstream outputFile_2D_pol1_t1("gnu_2D_pol1_t1_matrix_2sol_num.dat");
for(i=0;i<SPACE_pol;i=i+1)
{
outputFile_2D_pol1_t1 << x_begin + (i * h_pol) << setw(18);
outputFile_2D_pol1_t1 << pol1_t1_matrix[i][1] << setw(18);
outputFile_2D_pol1_t1 << endl;
}
outputFile_2D_pol1_t1.close();
ofstream outputFile_2D_pol1_t2("gnu_2D_pol1_t2_matrix_2sol_num.dat");
for(i=0;i<SPACE_pol;i=i+1)
{
outputFile_2D_pol1_t2 << x_begin + (i * h_pol) << setw(18);
outputFile_2D_pol1_t2 << pol1_t2_matrix[i][1] << setw(18);
outputFile_2D_pol1_t2 << endl;
}
outputFile_2D_pol1_t2.close();
ofstream outputFile_2D_pol1_t3("gnu_2D_pol1_t3_matrix_2sol_num.dat");
for(i=0;i<SPACE_pol;i=i+1)
{
outputFile_2D_pol1_t3 << x_begin + (i * h_pol) << setw(18);
outputFile_2D_pol1_t3 << pol1_t3_matrix[i][1] << setw(18);
outputFile_2D_pol1_t3 << endl;
}
outputFile_2D_pol1_t3.close();
etc.;
The above becomes very laborious if I have to do that more than a 100 times (at least up till t100
, but sometimes I'll have to do that 1000 times or more). So my question is: is there any way to do all of the above using (separate) loops?
Naively, I would assume it looks something like this (to replace the laborious "declaration of variables" as shown above):
for(i=1;i<101;i=i+1)
{
double (pol1_t"i"_matrix)[2] = new double[SPACE_pol][2];
}
and (to replace the laborious "writing to files" as shown above):
for(i=1;i<101;i=i+1)
{
ofstream outputFile_2D_pol1_t"i"("gnu_2D_pol1_t"i"_matrix_2sol_num.dat");
for(j=0;j<SPACE_pol;j=j+1)
{
outputFile_2D_pol1_t"i" << x_begin + (j * h_pol) << setw(18);
outputFile_2D_pol1_t"i" << pol1_tj_matrix[i][1] << setw(18);
outputFile_2D_pol1_t"i" << endl;
}
outputFile_2D_pol1_t"i".close();
}