在向量向量中找到 Point3f 的最大值

Find maximum for Point3f in vector of vector

本文关键字:向量 最大值 Point3f      更新时间:2023-10-16

我在这里看到了一个类似的问题,但我没有得到我想要的东西。我有这样的东西

vector< vector<Point3f> > 3dpoints;

现在假设我只想找到 x 坐标的最大值,并想打印与之关联的所有其他值。我像下面一样尝试,但它为成员"开始"抛出了一些错误请求......

for( auto r = 0; r < 3dpoints.size(); r++ ) {
    for( auto s = 0; s < 3dpoints[r].size(); s++ ) {
        cout<< max_element( 3dpoints[r][s].x.begin(), 3dpoints[r][s].x.end() ) << endl; 
    } 
}

我知道我错过了一些基本的东西,但无法得到它。谁能帮我在 Point3f 中找到最大值?

template<class F>
struct projected_order_t {
  F f;
  template<class Lhs, class Rhs>
  bool operator()(Lhs const& lhs, Rhs const& rhs)const {
    return f(lhs) < f(rhs);
  }
};
template<class F>
projected_order_t<F> projected_order(F f) {
  return {std::move(f)};
}
auto max_elem_of_vector = [](std::vector<Point3f> const& pts){
  return std::max_element( pts.begin(), pts.end(), projected_order(
    [](Point3f pt){ return pt.x; }
  ));
};
auto max_x_of_vector = [](std::vector<Point3f> const& pts){
  auto it = max_elem_of_vector(pts);
  if (it == pts.end()) return std::numeric_limits<float>::min();
  return it->x;
};
auto max_elem_of_v_of_v = [](std::vector<std::vector<Point3f>> const& pts){
  auto it = std::max_element( pts.begin(), pts.end(), projected_order(
    max_x_of_vector
  ));
  auto minf = std::numeric_limits<float>::min();
  auto minp = Point3f{minf, minf, minf};
  if (it == pts.end())
    return minp
  auto it2 = max_elem_of_vector(*it);
  if (it2 == it->end()) 
    return minp;
  return *it2;
};

max_elem_of_v_of_v应该可以解决您的问题。

投影

顺序采用投影(从类型 A 到类型 B 的映射(,并返回类型 A 上的排序,该排序使用映射到 B 并在 B<

第一种用途将点映射到其x坐标;这使我们能够通过x坐标在点向量中找到max元素。

第二种用法将点向量映射到该向量中任何元素的最大 x。 我们用它来找到具有最大 x 元素的向量。

然后,我们从具有最大x元素的最大向量中提取元素。

如果没有 min 元素,则返回最小浮点值。

您可以通过单次传递来做到这一点:

vector< vector<Point3f> > points;
vector<Point3f> maxes;
for( const auto &v : points ) {
    for( const auto &p : v ) {
        if( not maxes.empty() and maxes.front().x < p.x )
            maxes.clear();
        if( maxes.empty() or maxes.front().x == p.x )
            maxes.push_back( p );
    }
}
// here you have list of all points with max x in maxes

这是一个展示这个想法的例子,在你的代码中,你可能想用使用 epsilon 的函数替换 <和>

显示的PS代码对所有数据都这样做,您提到您需要单独为每一行执行此操作。可以轻松更改代码以执行此操作:

for( const auto &v : points ) {
    vector<Point3f> maxes;
    for( const auto &p : v ) {
        if( not maxes.empty() and maxes.front().x < p.x )
            maxes.clear();
        if( maxes.empty() or maxes.front().x == p.x )
            maxes.push_back( p );
    }
    // print maxes here
}

根据你最新的评论,代码应该是:

for( auto r = 0; r < 3dpoints.size(); r++ ) {
   auto highest = max_element(begin(3dpoints[r]), end(3dpoints[r]),
                              [](const Point3f &lhs, const Point3f &rhs) 
                                { return lhs.x < rhs.x; })
   cout << highest->y << highest->z << endl;
}

你做错了什么:

  • 3dpoints[r][s].x 是一个浮点数,没有 begin((/end((。
  • 您需要为max_element提供自定义比较功能。

编辑感谢@Slava指出 std::max_element 返回一个迭代器。