簡體   English   中英

我應該如何將此std :: array <>傳遞給函數?

[英]How should I pass this std::array<> to a function?

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作為引用傳遞,但它告訴我該類型的引用無法初始化。

您說您嘗試了參考,但失敗了。 我不知道為什么,因為那是正確的做法。

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;
}

您正在取消引用(currentPaths+1) ,其類型為std::array* (更准確地說:您是在遞增指針,然后訪問其指向的數據),而您可能想檢索currentPaths的第一個元素,即: currentPaths[0] (數組中的第一個索引為0)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM