您好我需要检查我的代码,因为它对我的分段错误。这是因为我的2D矢量没有分配内存,但我该怎么做呢?
std::vector <std::vector <std::string>> pdf_report::random_data (int num_entries, int report_type)
{
std::vector <std::vector <std::string>> printer_control;
int card_num_max = 999899, card_num_min = 100000; // card number
int vol_ent_max = 1000, vol_ent_min = 10; // volume entered
int vol_disp_max = 7, vol_disp_min = 0; // volume dispensed
int cn_type_max = 10, cn_type_min = 1; // card type
int charge_amt_max = 400, charge_amt_min = 2;
int vol_bal_max = 6000, vol_bal_min = 0;
int auth_num_max = 9999, auth_num_min = 1000;
srand (time (NULL)); // seed rand () with new values
switch (report_type)
{
case 1: // Report 1: Card Number, Volume Entered, Volume Dispensed
{
// fill a string array with random values
for (int k = 0; k < num_entries; k++)
{
int randNum = 0;
int randNum1 = 0;
int randNum2 = 0;
int randNum3 = 0;
// fill column 0 for Card Number
randNum = rand() % (card_num_max - card_num_min) + card_num_min; // generate random numbers inside range
printer_control [k][0] = int_to_str (randNum); // set string array element equal to converted int
// fill column 1 for Volume Entered
randNum1 = rand() % (vol_ent_max - vol_ent_min) + vol_ent_min; // generate random numbers inside range
printer_control [k][1] = int_to_str (randNum1); // set string array element equal to converted int
// fill column 2 for Volume Dispensed
randNum2 = rand() % (vol_disp_max - vol_disp_min); // generate random numbers inside range
randNum3 = randNum1 - randNum2; // volume dispensed could be lower than the number entered, but not higher
printer_control [k][2] = int_to_str (randNum3); // set string array element equal to converted int
}
break;
}
}
return printer_control;
}
我有更多的案例,但只需要一个工作就是我需要复制给其他人。谢谢您的帮助。
答案 0 :(得分:1)
从您的代码中,我假设printer_control是num_entries x 3
的矩阵。
要初始化vector<vector<string> >
,请执行以下操作:
printer_control.resize (num_entries);
for (int i=0; i<num_entries; i++)
printer_control[i].resize (3);