#include<fstream> #include<iostream> #include<string> #include<sstream> #include<list> using namespace std; //路由表中数据 class Table{ public: string destination_id; int distance; string next_stop; }; //路由类 class Route{ public: Route(); string open_file(ifstream& infile); void show(list<Table>& p); void change(); void update(); private: string route1; string route2; list<Table> piece1; list<Table> piece2; }; //类中的函数 //构造函数 Route::Route(){ string temp; Table r_temp; ifstream infile1,infile2; istringstream strm; cout<<"enter the current route name: "; route1=open_file(infile1); while(getline(infile1,temp)){ strm.str(temp); strm>>r_temp.destination_id>>r_temp.distance>>r_temp.next_stop; piece1.push_back(r_temp); strm.clear(); } cout<<" this is the currnet route contents "<<endl; show(piece1); cout<<"enter the neighbor route name: "; route2=open_file(infile2); while(getline(infile2,temp)){ strm.str(temp); strm>>r_temp.destination_id>>r_temp.distance>>r_temp.next_stop; piece2.push_back(r_temp); strm.clear(); } cout<<" this is the neighbor route contents "<<endl; show(piece2); } //打开文件函数 string Route::open_file(ifstream& infile){ string str; cin>>str; infile.open((str+".txt").c_str()); if(!infile){ cerr<<"file open error!"<<endl; exit(1); } return str; } //显示每条信息 void Route::show(list<Table>& p){ for(list<Table>::iterator it=p.begin();it!=p.end();it++) cout<<(*it).destination_id<<" "<<(*it).distance<<" " <<(*it).next_stop<<endl; } //改变piece2 void Route::change(){ for(list<Table>::iterator it=piece2.begin();it!=piece2.end();it++){ ((*it).distance)++; (*it).next_stop=route2; } cout<<" this is the changed neighbor route contents "<<endl; show(piece2); } //更新piece1 void Route::update(){ int count=0; //计数器,用来表示id2是否出现与id1中 list<Table>::iterator it1=piece1.begin(); list<Table>::iterator it2=piece2.begin(); for(;it2!=piece2.end();it2++){ for(it1=piece1.begin();it1!=piece1.end();it1++){ if((*it1).destination_id==(*it2).destination_id){ count++; if(((*it1).next_stop)==((*it2).next_stop)){ (*it1).distance=(*it2).distance; (*it1).next_stop=(*it2).next_stop; } if(((*it1).next_stop!=(*it2).next_stop)&&((*it1).distance>(*it2).distance)){ (*it1).distance=(*it2).distance; (*it1).next_stop=(*it2).next_stop; } } } if(count==0) piece1.push_back(*it2); count=0; } cout<<" this is the updated current route contents "<<endl; show(piece1); } int main(){ Route route; route.change(); route.update(); return 0; } 然后在同一文件加下添加两个txt文件,可以命名为Rc和Rn。里面分别存入如下信息 Rc: net1 1 R1 net0 9 R4 net4 5 R4 net5 8 Rn net6 6 R0 net7 9 R4 Rn: net2 3 R2 net1 1 R5 net3 6 R2 net4 10 R3 net5 5 R2 net6 6 R1 内容只是用来测试的。运行程序时只需要输入文件名,即Rc,Rn即可。
|