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