今天我遇到一個奇怪的問題。我的C++代碼可以在調試模式下工作。 使用g ++ -g編譯代碼。但是,當我使用g ++ -O來優化代碼。它會卡住某處。看起來有死循環。有誰知道如何找到這種錯誤?當我用DDD debuger調試代碼時,它工作正常。謝謝!如何找到G ++優化C++代碼的錯誤?
代碼的一部分(我找到這部分就被卡住)下方粘貼:
void Solver::reduceRoutes()
{
int V=pinst->get_V(); //get the given number of vehicles
if(int(curSol_.size())<=V) // return when solution has no extra routes
return;
int routeNum1,routeNum2; // the two routes modified
listSize=int(0.2*pinst->get_N());
short TheNode,anode; // the second node
float totalInc; //the obj increase of a candidate position
Route::iterator it;
vector<short> candidateList;
vector<short> validCandidateList; //nodes can be moved to
vector<float> totalImpList;
int solSize=int(curSol_.size());
while(solSize>V)
{
// cout <<"debug6.0 ";
routeNum1=psol->findRouteWithMinC(curSol_);
cout <<" debug6.1 "<<curSol_.size()<<" "<<routeNum1;
while(curSol_[routeNum1].size()>2)
{
it=curSol_[routeNum1].begin();
it++;
TheNode=*it;
candidateList=pinst->get_PNL(TheNode,listSize);
// evaluate the effect of moving the node to each possible position
for(unsigned int i=1;i<candidateList.size();i++) //the first node is itself
{
anode=candidateList[i];
routeNum2=RouteNumList[anode]; //find the route of second node
if(routeNum2!=routeNum1) //inter route move
{
totalInc=evaluateAreduceRouteMove(curSol_,routeNum1,routeNum2,TheNode,anode);
totalImpList.push_back(totalInc);
validCandidateList.push_back(anode);
}
}
//find the best position to insert the
int ii=(min_element(totalImpList.begin(),totalImpList.end())-totalImpList.begin());
anode=validCandidateList[ii];
it=find(curSol_[routeNum1].begin(),curSol_[routeNum1].end(),TheNode);
curSol_[routeNum1].erase(it); //remove from route1
routeNum2=RouteNumList[anode];
it=find(curSol_[routeNum2].begin(),curSol_[routeNum2].end(),anode);
++it;
curSol_[routeNum2].insert(it,TheNode); //insert to the second route
RouteNumList[TheNode]=routeNum2; //update route number
//improve the modified routes
psol->doTwoOpt(curSol_[routeNum2]);
totalImpList.clear();
validCandidateList.clear();
}
//update route number list
for(unsigned int i=routeNum1+1;i<curSol_.size();i++)
{
for(it=curSol_[i].begin();it!=curSol_[i].end();it++)
RouteNumList[*it]-=1;
}
RouteNumList[0]=0;
// eliminate the empty route
curSol_.erase(curSol_.begin()+routeNum1);
solSize=curSol_.size();
cout <<" debug6.3 "<<solSize<< " \n";
}
return;
}
感謝您回答我的問題。現在我的代碼沒有進行優化。我只是想知道優化器做了什麼,因此代碼工作。如果優化模式不能提高速度,那麼可以不使用它。任何人都可以評論優化模式的力量嗎? 再次感謝。
請將您的所有代碼縮進四個空格,它會將其放入一個代碼塊中。 – Jasper 2010-08-26 20:26:29
開始的提示:爲了可讀性分解爲不同的功能。聲明它們時初始化所有變量。不要重複使用同一個變量來實現多種目的。使用已檢查的STL版本運行,以確保您不會在迭代器指向已修改的容器時發生錯誤(常見問題) – 2010-08-26 20:36:36
@Greg:同意。當它不回答問題時,只接受任何垃圾作爲答案是沒有意義的。 – 2010-09-01 17:06:07