struct lessDion
{
int m, M;
lessDion(int m, int M):m(m),M(M){};
bool operator()(int a, int b)
{
bool a_in = (a >= m && a <= M);
bool b_in = (b >= m && b <= M);
if (a_in && !b_in) return true;
if (b_in && !a_in) return false;
return a < b;
}
};
int main(int argc, char * argv[])
{
vector<int> v{1,0,5,7,12,4,-1,22};
cout << *min_element(v.begin(),v.end(),lessDion(3,6));
}
#include <iostream>
#include <climits>
#include <vector>
int minValue(const std::vector<int> & values, int min, int max, bool & found) {
found = false;
int last = INT_MAX;
for (auto val: values) {
if ((val <= max) && (val >= min)) {
found = true;
if (val < last) {
last = val;
}
}
}
return last;
};
int main()
{
std::vector<int> myVector = { 1, 2, 3, 25, 26, 27, 40, 50, 51 };
bool found;
int min = minValue(myVector, 26, 30, found);
if (found) {
std::cout << "minimal range value is: " << min << std::endl;
} else {
std::cout << "sorry there no value in range" << std::endl;
}
return 0;
}
有理由
min_element排序吗?如果我们谈论的是一系列 VALUES,那么,例如,像这样:
如果关于 INDEXES 的范围,那么
Lambda 被证明是最成功的选择。该解决方案可以进一步优化。我知道)感谢科瓦迪姆同志