簡體   English   中英

使用基於范圍的循環迭代向量時出現問題

[英]Problem while iterating a vector using range-based loop

我正在使用 PCL 庫對 RANSAC 進行基本實現。 雖然,這里的問題僅與 C++ 概念有關。

我以兩種方式迭代點雲; 一個工作完美,另一個迭代不到一半的點。 我只想了解兩者之一不起作用的原因。

工作一:

    for (int index=0; index < cloud->points.size(); index++)
    {
        float distance = abs(A * cloud->points[index].x + B * cloud->points[index].y + C * cloud->points[index].z + D) / sqrt(A * A + B * B + C * C);

        // Check for the two points set above, if present ignore
        if (set_inliers.count(index) > 0)
            continue;

        // If distance is smaller than threshold count it as inlier
        if (distance <= distanceTol)
            set_inliers.insert(index);

        std::cout << "Point Number: " << index << std::endl;
    }

不起作用的循環:

int index = 0;

for (auto elem : cloud->points)
{
    float distance = abs(A * elem.x + B * elem.y + C * elem.z + D) / sqrt(A * A + B * B + C * C);

    // Check for the two points set above, if present ignore
    if (set_inliers.count(index) > 0)
        continue;

    // If distance is smaller than threshold count it as inlier
    if (distance <= distanceTol)
        set_inliers.insert(index);

    std::cout << "Point Number: " << index << std::endl;
    index++;
} 

cloud->points 是一個向量(見下文)。 因此,C++11 中引入的基於范圍的循環應該可以工作,並且上面提到的兩個循環應該是相同的,對吧? 我想我在這里錯過了一些東西。

變量詳細信息:

在上面的代碼中,var cloud 被聲明為:

 pcl::PointCloud<pcl::PointXYZ>::Ptr cloud

Ptr 是以下向量:

 std::vector<pcl::PointXYZ, Eigen::aligned_allocator<pcl::PointXYZ>

cloud->points 定義為:

 std::vector<PointT, Eigen::aligned_allocator<PointT> > pcl::PointCloud< PointT >::points

供參考: PCL 點雲參考

我在這里有一些理解問題,因此如果有人能幫忙就太好了!

非常感謝!

如果沒有完整的代碼示例,很難說,但是兩個循環中有一件事是不同的。 我們刪除的所有其他內容

for (int index=0; index < cloud->points.size(); index++) { 
    if (some_condition) continue;
    // use index
}

對比

int index = 0;
for (auto elem : cloud->points) {
    if (some_contition) continue;
    // use index
    index++;
}

在基於范圍的 for 循環中,當some_condition == true時,索引不會遞增。 在基於索引的循環中, index在每次迭代時遞增。 我想這兩個循環實際上確實具有相同的迭代次數,但是在基於范圍的循環之后index將具有不同的值。

基於范圍的循環的花式設施仍然相當稀缺。 如果您不想求助於 boost 或其他第三方庫,我建議您在需要索引時使用基於索引的循環。 當您不關心索引時,基於范圍的循環很好。

第二個循環有一個continue ,有機會跳過index++ 如果發生這種情況,索引值將永遠無法引用末尾的點。

看起來您希望index無條件地隨着每次循環迭代而遞增。 最簡單的更改是將continue替換為

{
    index++;
    continue;
}

暫無
暫無

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

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