[英]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;
}
At both those statements I'm getting the same error: no suitable conversion from std::array<LINE,10U>*currentPaths to LINE
. 在这两个语句中,我都得到了相同的错误:
no suitable conversion from std::array<LINE,10U>*currentPaths to LINE
。 Why is this so? 为什么会这样呢? Should I pass the array another way?
我应该以其他方式传递数组吗? I've also tried passing currentPaths as a reference, but it tells me that a reference of the type cannot be initialized.
我也尝试过将currentPaths作为引用传递,但它告诉我该类型的引用无法初始化。
You said you tried a reference and it failed. 您说您尝试了参考,但失败了。 I don't know why, because that was the correct thing to do.
我不知道为什么,因为那是正确的做法。
LINE CShortestPathFinderView::shortestLine(std::array<LINE,10> ¤tPaths);
From the sounds of it, you also used a reference for the temporary variable. 从它的声音来看,您还为临时变量使用了参考。 That's wrong.
错了
std::array<LINE,10>& currentPaths = PossibleStrtPaths(); // WRONG
std::array<LINE,10> currentPaths = PossibleStrtPaths(); // RIGHT
LINE s = shortestLine(currentPaths);
And finally, the first element is number zero. 最后,第一个元素是数字零。 The subscripting operator
[]
is preferred when you are doing array access. 下标运算符
[]
是进行数组访问时的首选。 So: 所以:
LINE s = currentPaths[0];
But you also can easily get the first item from the iterator. 但是您也可以轻松地从迭代器中获取第一项。
Final code: 最终代码:
/* 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.