繁体   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