首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >我应该如何将这个std::array<>传递给一个函数?

我应该如何将这个std::array<>传递给一个函数?
EN

Stack Overflow用户
提问于 2012-12-28 14:09:58
回答 2查看 2.6K关注 0票数 2
代码语言:javascript
复制
std::array<LINE,10> currentPaths=PossibleStrtPaths();
LINE s=shortestLine(currentPaths);                       //ERROR

代码语言:javascript
复制
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作为引用传递,但它告诉我不能初始化类型的引用。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-12-28 14:17:10

你说你试过推荐信但失败了。我不知道为什么,因为那是正确的做法。

代码语言:javascript
复制
LINE CShortestPathFinderView::shortestLine(std::array<LINE,10> &currentPaths);

根据它的声音,您还使用了对临时变量的引用。这是错误的。

代码语言:javascript
复制
std::array<LINE,10>& currentPaths = PossibleStrtPaths(); // WRONG
std::array<LINE,10>  currentPaths = PossibleStrtPaths(); // RIGHT
LINE s = shortestLine(currentPaths);

最后,第一个元素是零。在进行数组访问时,首选订阅运算符[]。所以:

代码语言:javascript
复制
LINE s = currentPaths[0];

但是,您也可以很容易地从迭代器获得第一项。

最终代码:

代码语言:javascript
复制
/* 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;
}
票数 4
EN

Stack Overflow用户

发布于 2012-12-28 14:15:20

您正在取消引用(currentPaths+1),它的类型为std::array* (更准确地说:您正在递增指针,然后访问其指向的数据),而您可能希望检索currentPaths的第一个元素,即:currentPaths[0] (数组中的第一个索引为0)。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14070756

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档