gpt4 book ai didi

c++ - 使用基于范围的循环迭代 vector 时出现问题

转载 作者:行者123 更新时间:2023-12-01 15:13:32 26 4
gpt4 key购买 nike

我正在使用PCL lib进行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是一个 vector (请参阅下文)。因此,C++ 11中引入的基于范围的循环应该可以工作,并且上面提到的两个循环应该相同,对吗?我想我在这里错过了一些东西。

变量详细信息:

在上面的代码中,var cloud声明为:
 pcl::PointCloud<pcl::PointXYZ>::Ptr cloud

Ptr是以下各项的 vector :
 std::vector<pcl::PointXYZ, Eigen::aligned_allocator<pcl::PointXYZ>

cloud-> points定义为:
 std::vector<PointT, Eigen::aligned_allocator<PointT> > pcl::PointCloud< PointT >::points

供引用: PCL Point Cloud Reference

我在这里有一些理解上的问题,因此如果有人可以提供帮助,那就太好了!

非常感谢!

最佳答案

没有完整的代码示例,很难说,但是在两个循环中有一点不同。其他一切我们都删除了

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或其他第三方库,我建议您在需要索引时使用基于索引的循环。当您不关心索引时,基于范围的循环会很好。

关于c++ - 使用基于范围的循环迭代 vector 时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59897837/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com