gpt4 book ai didi

c++ - 查找点 vector 的最小值和最大值

转载 作者:太空狗 更新时间:2023-10-29 23:51:51 24 4
gpt4 key购买 nike

我想从点 vector 中找到最小值和最大值。该 vector 由 x 和 y 元素类型组成。我想要 x 的最小值和最大值以及 y 的最小值。我的 vector 定义为:

 std::vector<cv::Point> location;
findNOZeroInMat(angles,location);

//I tried to use but it gives an error
minMaxLoc(location.cols(0), &minVal_x, &maxVal_x);
minMaxLoc(location.cols(1), &minVal_y, &maxVal_y);

我也尝试了 location.x,但没有成功。如何分别获取 x 和 y 的最小值和最大值?

最佳答案

您可以使用 std::minmax_element使用自定义小于比较函数/仿函数:

#include <algorithm>

bool less_by_x(const cv::Point& lhs, const cv::Point& rhs)
{
return lhs.x < rhs.x;
}

然后

auto mmx = std::minmax_element(location.begin(), location.end(), less_by_x);

y 也类似。 mmx.first 将有一个指向最小元素的迭代器,mmx.second 将有一个指向最大元素的迭代器。

如果您没有对 auto 的 C++11 支持,您需要明确说明:

typedef std::vector<cv::Point>::const_iterator PointIt;
std::pair<PointIt, PointIt> mmx = std::minmax_element(location.begin(),
location.end(),
less_by_x);

但请注意,std::minmax_element 需要 C++11 库支持。

关于c++ - 查找点 vector 的最小值和最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18438706/

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