minmax_element のドキュメントから、イテレータのペアを返すことがわかります。
与えられた:
vector<Point> pts = ...
auto mmx = std::minmax_element(pts.begin(), pts.end(), less_by_y);
mmx.first
で min 要素へのイテレータ、 で max 要素へのイテレータにアクセスできますmmx.second
。
最小値と最大値を取得する場合は、次のようにy
する必要があります。
int min_y = mmx.first->y;
int max_y = mmx.second->y;
y
OpenCV を使用しているため、次を使用して値を見つけることもできますboudingRect
。
Rect box = boundingRect(pts);
std::cout << "min y: " << box.tl().y << std::endl;
std::cout << "max y: " << box.br().y - 1 << std::endl; // Note the -1!!!
これはおそらく遅くなりますが、カスタム比較関数を定義する必要はありません。これは、必要に応じて min と max も計算しx
ます。
ここに完全な例があります:
#include <opencv2/opencv.hpp>
#include <algorithm>
#include <iostream>
using namespace cv;
bool less_by_y(const cv::Point& lhs, const cv::Point& rhs)
{
return lhs.y < rhs.y;
}
int main(int argc, char** argv)
{
// Some points
vector<Point> pts = {Point(5,5), Point(5,0), Point(3,5), Point(3,7)};
// Find min and max "y"
auto mmx = std::minmax_element(pts.begin(), pts.end(), less_by_y);
// Get the values
int min_y = mmx.first->y;
int max_y = mmx.second->y;
// Get the indices in the vector, if needed
int idx_min_y = std::distance(pts.begin(), mmx.first);
int idx_max_y = std::distance(pts.begin(), mmx.second);
// Show results
std::cout << "min y: " << min_y << " at index: " << idx_min_y << std::endl;
std::cout << "max y: " << max_y << " at index: " << idx_max_y << std::endl;
// Using OpenCV boundingRect
Rect box = boundingRect(pts);
std::cout << "min y: " << box.tl().y << std::endl;
std::cout << "max y: " << box.br().y - 1 << std::endl; // Note the -1!!!
return 0;
}