如何用STL mimax算法替换我的'for'循环来找到min/max

And*_*dre 4 c++ algorithm stl minmax

我必须从a中找到最小值/最大值(min x,min y,max x,max y)

vector<cv::Point>
Run Code Online (Sandbox Code Playgroud)

这是我的代码:

vector<cv::Point> contour;
Run Code Online (Sandbox Code Playgroud)

...

Min = Point(640, 480) ;
Max = Point(0,0) ;
for (int j=0; j<(int)contour.size(); j++)
{
    if (contour[j].x < Min.x) Min.x = contour[j].x ;
    if (contour[j].y < Min.y) Min.y = contour[j].y ;
    if (contour[j].x > Max.x) Max.x = contour[j].x ;
    if (contour[j].y > Max.y) Max.y = contour[j].y ;
}
Run Code Online (Sandbox Code Playgroud)

这很好用.我使用mimmax STL开发了一个版本:

auto XminXmax = minmax_element(contour.begin(), contour.end(), [](Point p1,Point p2) {return p1.x < p2.x; });
auto YminYmax = minmax_element(contour.begin(), contour.end(), [](Point p1,Point p2) {return p1.y < p2.y; });
Point Min = Point((*XminXmax.first).x, (*YminYmax.first).y );
Point Max = Point((*XminXmax.second).x, (*YminYmax.second).y );
Run Code Online (Sandbox Code Playgroud)

这也很好,并给出相同的结果.但是,由于算法minmax被调用两次,执行时间是两次.是否可以通过一次调用minmax算法来优化它?

Jua*_*eni 6

minmax_elementPoint对象上运行比较并返回Point对象.

xy值是独立的,它是可能的min(x),并min(y)会属于不同的对象.

我会for range用于这种特殊情况.

Min = Point(640, 480) ;
Max = Point(0,0) ;
for (auto &p : contour)
{
    Min.x = std::min(p.x, Min.x)
    Min.y = std::min(p.y, Min.y)
    Max.x = std::max(p.x, Max.x)
    Max.y = std::max(p.y, Max.y)
}
Run Code Online (Sandbox Code Playgroud)