从特征点获取max x,max y,max z

时间:2018-01-08 16:42:32

标签: c++

我有std::vector<Ogre::Vector3> featurePointsOgre::Vector3有x,y,z float个成员。

我想获得max x,min x,max y,min y,max z和min z。

我尝试了以下内容:

float maxX = std::max_element(featurePoints.begin(), featurePoints.end(),
                             [](Ogre::Vector3 a, Ogre::Vector3 b){return a.x < b.x;});
auto maxx = std::max_element(featurePoints.begin(), featurePoints.end(),
                             [](Ogre::Vector3 a, Ogre::Vector3 b){return a.x < b.x;});
auto maxy = std::max_element(featurePoints.begin(), featurePoints.end(),
                             [](Ogre::Vector3 a, Ogre::Vector3 b){return a.y < b.y;});
auto maxz = std::max_element(featurePoints.begin(), featurePoints.end(),
                             [](Ogre::Vector3 a, Ogre::Vector3 b){return a.z < b.z;});
auto minx = std::max_element(featurePoints.begin(), featurePoints.end(),
                             [](Ogre::Vector3 a, Ogre::Vector3 b){return a.x > b.x;});
auto miny = std::max_element(featurePoints.begin(), featurePoints.end(),
                             [](Ogre::Vector3 a, Ogre::Vector3 b){return a.y > b.y;});
auto minz = std::max_element(featurePoints.begin(), featurePoints.end(),
                             [](Ogre::Vector3 a, Ogre::Vector3 b){return a.z > b.z;});

这给出了这个编译错误:

  

没有可行的从'std :: __ 1 :: __ wrap_iter'转换为'float'

我该如何解决?

2 个答案:

答案 0 :(得分:1)

std::max_element返回容器的迭代器,因此您可以分配它然后取消引用以获取元素

auto itMax = std::max_element(featurePoints.begin(), featurePoints.end(), [](Ogre::Vector3 a, Ogre::Vector3 b){return a.x < b.x;});
float maxX = itMax->x;

或直接取消引用

float maxX = std::max_element(featurePoints.begin(),
                              featurePoints.end(),
                              [](Ogre::Vector3 a, Ogre::Vector3 b){return a.x < b.x;})->x;
float minX = std::min_element(featurePoints.begin(),
                              featurePoints.end(),
                              [](Ogre::Vector3 a, Ogre::Vector3 b){return a.x < b.x;})->x;

答案 1 :(得分:1)

std::max_element的返回值是容器中元素的迭代器,而不是元素本身。因此,编译器在尝试将结果分配给float时会发出诊断信息。

但是有一个更好的功能:std::minmax_element允许你在一次遍历中获得最小值和最大值:

auto pair = std::minmax_element(
    featurePoints.begin(),
    featurePoints.end(),
    [](Ogre::Vector3 a, Ogre::Vector3 b){return a.x < b.x;}
);
float minX = pair.first->x;
float maxX = pair.second->x;

这里,pair是两个迭代器的std::pair,第一个是最小的迭代器,第二个是最大的迭代器。

参考:http://en.cppreference.com/w/cpp/algorithm/minmax_element