2012-12-28 24 views
2
std::array<LINE,10> currentPaths=PossibleStrtPaths(); 
LINE s=shortestLine(currentPaths);      //ERROR 

LINE CShortestPathFinderView::shortestLine(std::array<LINE,10> *currentPaths) 
{ 
std::array<LINE,10>::iterator iter; 

LINE s=*(currentPaths+1);      //ERROR 

for(iter=currentPaths->begin()+1;iter<=currentPaths->end();iter++) 
{ 
    if(s.cost>iter->cost) 
    s=*iter; 
} 

std::remove(currentPaths->begin(),currentPaths->end(),s); 

    //now s contains the shortest partial path 
return s; 


} 

在這兩個語句我得到了同樣的錯誤:no suitable conversion from std::array<LINE,10U>*currentPaths to LINE。這是爲什麼?我應該以另一種方式通過陣列嗎?我也嘗試通過currentPaths作爲參考,但它告訴我該類型的引用無法初始化。我應該如何將這個std :: array <>傳遞給函數?

+0

'*(currentPaths + 1);'你能做到嗎?或者你的意思是'(* currentPaths)[1]' – andre

+0

@ahenderson我想將_currentPaths_的第二個LINE對象賦給_s_。是不是'*(currentPaths + 1)'與'currentPaths [1]'相同? – Ghost

+0

除非'null'是通過引用傳遞的可能值,否則最好走。使用你的方法,你可能正在訪問'(currentPaths)[10]',這與currentPaths [1]'相同。記住你有一個指向數組而不是數組的指針。 – andre

回答

4

你說你嘗試了一個參考,它失敗了。我不知道爲什麼,因爲那是正確的事情。

LINE CShortestPathFinderView::shortestLine(std::array<LINE,10> &currentPaths); 

從它的聲音中,您還使用了臨時變量的引用。這是錯誤的。

std::array<LINE,10>& currentPaths = PossibleStrtPaths(); // WRONG 
std::array<LINE,10> currentPaths = PossibleStrtPaths(); // RIGHT 
LINE s = shortestLine(currentPaths); 

最後,第一個元素是數字零。當您在進行數組訪問時,首選下標運算符[]。所以:

LINE s = currentPaths[0]; 

但是你也可以很容易地從迭代器中獲得第一項。

最終代碼:

/* precondition: currentPaths is not empty */ 
LINE CShortestPathFinderView::shortestLine(std::array<LINE,10>& currentPaths) 
{ 
    std::array<LINE,10>::iterator iter = currentPaths.begin(); 
    LINE s = *(iter++); 

    for(; iter != currentPaths->end(); ++iter) { 
     if(s.cost>iter->cost) 
      s=*iter; 
    } 

    std::remove(currentPaths.begin(), currentPaths.end(), s); 

    //now s contains the shortest partial path 
    return s; 
} 
+0

我已經插入了你給我的代碼,但是我仍然在'LINE s = shortestLine(currentPaths); ':'error C2664:'CShortestPathFinderView :: shortestLine':無法將參數1從'std :: tr1 :: array <_Ty,_Size>'轉換爲'std :: tr1 :: array <_Ty,_Size>&'' – Ghost

+0

@Ghost:顯示*整個*錯誤消息,包括什麼'_Ty'和'_Size'。我想知道您是否有多個名爲'LINE'的類型。 –

+0

[ 1> _Ty = CShortestPathFinderView ::腦:: LINE, 1> _size = 10 1>] 1>和 1> [ 1> _Ty = LINE, 1> _size = 10 1> ] Brains()是我打電話給_shortestLine_的函數。 – Ghost

0

您提領(currentPaths+1)這是std::array*型的(更確切地說:你是遞增的指針,然後訪問其所指的數據),而你可能要檢索的currentPaths的第一要素,那就是:currentPaths[0](第一指數一個數組是0)。

相關問題