2015-10-28 26 views
-1

我正在編寫一個C++代碼,以根據站在那裏的交通工具數量計算交叉路口的交通燈時間。這部分是使用IVC技術獲得的,但爲了本示例的目的,手動提供。我面臨的問題是我想將每個通道的等待時間(max_time)存儲在數組中,但是由於用戶可能會選擇無限次地運行此代碼而不停止,並且無法聲明無限長數組,我不知道該怎麼做,任何幫助都會很棒,謝謝。 `用於計時交通信號燈的C++代碼

#include<iostream> 
#include<conio.h> 

using namespace std; 

int main() 
{ 
    int num_vehicles; 
    int t; 
    int max_time; 
    int timer;    //I need to initialize timer in such a way and as such an entity that its keeps resizing itself . 
    int add; 

while(1) 
{ 
    cout<<"Enter the number of vehicles at the red light: "; 
    cin>>num_vehicles; 
    cout<<"\n"; 

    if(num_vehicles<30) 
     timer=num_vehicles; 

    else if(num_vehicles>=30) 
    { 
     timer=num_vehicles/2; 
     add=num_vehicles/2; 
    }   

    cout<<"The red light turns green for "<<num_vehicles<<" number of time steps.\n\n"; 

    if(t=0) 
    { 
     cout<<"Total waiting time for first car at current red light since entry into system: 0"; 
    } 

    else if(t=1) 
    { 
     cout<<"Total waiting time for first car at current red light since entry into system: ";/*timer for first green light*/cout<<"\n\n"; 
    }   

    else if(t=2) 
    { 
     cout<<"Total waiting time for first car at current red light since entry into system: ";/*timer for first green light+second green light*/cout<<"\n\n"; 
    } 

    else 
    { 
     cout<<"Total waiting time for first car at current red light since entry into system: ";/*sum of timers for last three green lights*/cout<<"\n\n"; 
    } 

    t++;  

    cout<<"Moving to the next traffic light in clockwise order.\n\n\n\n"; 
} 

return 0; 
} 

`

+0

我不認爲你應該在新代碼中使用'conio.h' ...特別是因爲你沒有在任何地方使用它的功能。 – szczurcio

+0

您不能在任何數據結構中存儲無限數量的條目。最終你會耗盡記憶。在這種情況發生之前,std :: vector是一個很好的選擇。 –

+0

一旦指定車道的燈變綠,您不再需要該車道的等待時間,因此您可以清除陣列並重新開始。 –

回答

0

任何東西不能被申報無限存儲大小,但 減輕溢流使用 std::vector的風險或通過具有用戶輸入大小動態地聲明陣列。

使用向量:

申報定時器作爲​​和push_back()值以它用於存儲。