求向量中的最大值和最小值



我想做的是检查x的最大和最小元素。

我有地址

adress是在代码顶部写的矢量,x代表第一个数字,t代表行,i代表列。想要比较x值,并获得介于0和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 

让我们假设我们有一个x/y对的向量,我们想找到那些具有最小和最大x值的向量。我们可以用std::minmax_element(或std::minmax,尽管在这种情况下它有点笨拙,IMO(来做这件事,这是一个大致的顺序:

#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";
}

顺便说一句,我还注意到这对:[04,20]是可以的,但应该注意的是,前导的0意味着第一个数字实际上是以八进制给出的,而不是十进制。在这种情况下(个位数小于8(,它们是等效的,但类似112, 011(使用0将两者都填充到三位数(的结果最初可能会有些令人惊讶(在十进制中,第二个数字实际上是9,而不是11(。

最新更新