我遇到了一个问题,试图将我的算法推广到任何大小的问题。该代码适用于我使用的测试问题,但我必须手动插入一些数组的长度。接下来,我尝试在两个变量中读取输入文件的长度,但是我无法在我的所有代码中使用它们,而只是在某些部分中使用它们。我认为这是一件很愚蠢的事情,但我对 C++ 真的很陌生,我想获得帮助。这是一段代码:
#include <fstream>
#include <iostream>
#include <time.h>
using namespace std;
struct node{
int last_prod;
int last_slot;
float ZL;
float ZU;
float g;
bool fathomed;
node *next;
node *padre;
node *primofiglio;
};
clock_t start, end;
double cpu_time_used;
int l=0;
int cont_slot=0;
int cont_prod=0;
float temp_cont;
float distanze[360]; // dichiarazione variabili
int slot[111];
int slot_cum[111];
float COIp[111];
int domanda[111];
float Zb=9999999999999999;
float LowerBound(struct node *n);
float UpperBound(struct node *n);
float h(struct node *l,struct node *n);
void creasottolivello(struct node *n);
void fathRule2(struct node *n);
void fathRule3(struct node *n);
void stampaRisultati(struct node *n, ofstream &f);
int unFathomedNodes(struct node *n);
void append(struct node* temp, struct node* n);
void ricercaOttimo(struct node *n, ofstream &f);
void calcoloBounds(struct node *n);
int main(){
start = clock();
ifstream contdist_file ( "/Users/MarcoBi/Desktop/TESI di LAUREA/Xcode/dati/distanze.txt" ); // conteggio dati input
if ( !contdist_file.is_open() ) { //conta righe file slot
}
else {
for(int i=0; !contdist_file.eof(); i++){
contdist_file >> temp_cont;
cont_slot++;
}
}
ifstream contslot_file ( "/Users/MarcoBi/Desktop/TESI di LAUREA/Xcode/dati/slot.txt" );
if ( !contslot_file.is_open() ) { //conta righe file prodotti
}
else {
for(int i=0; !contslot_file.eof(); i++){
contslot_file >> temp_cont;
cont_prod++;
}
}
....
如您所见,在 main() 中,我将输入文件的长度计入 cont_prod 和 cont_slot 变量中,但是我不能在变量声明中使用它们。我需要的可变长度数组必须是全局变量,因为我在其他函数中也需要它们。而且 cont_prod 和 cont_slot 也需要是全局的,因为我在某些函数的局部变量声明中需要它们。这是我需要在其中使用它们的功能之一:
float LowerBound(struct node *n){ //funzione LowerBound
int S[111];
int Sp=0;
float d[111];
float dmin[111];
float D;
float LB;
for(int i=n->last_prod;i<111;i++){
Sp=Sp+slot[i];
}
for(int i=0;i<111;i++){ //Calcolo S_pigreco
S[i]=0;
}
if(n->last_prod==0){ //condizione necessaria per nodo radice
S[0]=slot[0];
for(int i=n->last_prod +2;i<111;i++){
for(int j=n->last_prod +1;j<=i;j++){
S[j]=S[j-1]+slot[j];
}
}
}
else{
for(int i=n->last_prod +1;i<111;i++){
for(int j=n->last_prod;j<=i;j++){
S[j]=S[j-1]+slot[j];
}
}
}
S[110]=S[109] + slot[110];
//calcolo somma distanze da slot j+1 a q
for(int i=0;i<111;i++){
d[i]=0;
}
for(int j=n->last_prod;j<111;j++){
for(int i=n->last_slot; i < n->last_slot +S[j]; i++){
d[j]=d[j]+distanze[i];
}
}
//calcolo dmin_pigreco
for(int i=n->last_prod; i<111; i++){
dmin[i]= d[i]/S[i];
}
D=0;
for(int i=n->last_prod; i<111; i++){
D=D+dmin[i]*domanda[i];
}
LB=n->g+2*D;
return LB;
}
111 是 cont_prod,360 是 cont_slot。我在 Xcode 的 Mac 上编程,它说变量长度数组不能在文件范围内声明,我认为这意味着全局变量。我该如何管理?