简体   繁体   中英

find the maximum and minimum value in vector

I want to do is to check whether an maximum and minimum element of x.

i have address

adress was vector written top of the code x stand for first number, t for row and i for column. want compare x value, and get maximum and minimum number which is between the 0 and 100

[28,13],[48,10],[48,81],[48,54],[48,0],[10,20]
[48,13],[38,10],[58,81],[48,54],[48,0],[40,20]
[18,13],[28,10],[68,81],[48,54],[48,0],[04,20]
... 
int maxH =100;
int minH = 0;
for (t = 0, t < 12, t++){
     for (i = 0, i < 6, i++){
        if(minH > addresss.(t).(i).x){
           minH = addresss.(t).(i).x;
        }
        if(maxH < addresss.(t).(i).x){
           maxH = addresss.(t).(i).x;
        }
     }
}
if statement not working 

Let's assume we have a vector of x/y pairs, and we want to find those that have the smallest and largest x values. We could do this with std::minmax_element (or std::minmax , though in this case it's a tiny bit clumsier, IMO), something on this general order:

#include <vector>
#include <algorithm>
#include <iostream>

struct Point {
    int x;
    int y;

    bool operator<(Point const &other) const { 
        return x < other.x;
    }
};

std::vector<Point> points {
    {28,13},{48,10},{48,81},{48,54},{48,0},{10,20},
    {48,13},{38,10},{58,81},{48,54},{48,0},{40,20},
    {18,13},{28,10},{68,81},{48,54},{48,0},{04,20}
};

int main() {
    auto pos = std::minmax_element(points.begin(), points.end());

    std::cout << "Smallest X: [" << pos.first->x << ", " << pos.first->y << "]\n";
    std::cout << "Largest X: [" << pos.second->x << ", " << pos.second->y << "]\n";
}

As an aside, I'd also note that the pair: [04,20] is all right as it stands, but it should be noted that the leading 0 means that the first number is actually given in octal, not decimal. In this case (single digit less than 8) those are equivalent, but something like 112, 011 (using 0 to fill both out to three digits) would give results that might initially be somewhat surprising (in decimal, the second number is actually 9 , not 11 ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM