I have a vector of QPointF
and I need to find the minimum and maximum y
values because I need to know what is the amplitude of the data in the vector.
I use QPointF but for adding each new element I sum up the x
value of other elements in the vector:
std::vector<QPointF> points;
int getTotalTime() {
int time = 0;
for(QPointF& p : points) {
time += p.x();
}
return time;
}
void addPointToGraph(const QPointF& p) {
if(points.size() == 0) {
points.push_back(p);
return;
}
points.push_back(QPointF(getTotalTime() + p.x(), p.y()));
}
So therefore I will have a continues waveform...this works fine! But now I need to find the amplitude of the waveform so I need to find minimum and maximum y
values of the points
vector.
E.g. I need a function to return min y
and max y
like a std::pair<float,float>
I have seen in the algorithm header we have something like:
std::array<int,7> foo {3,7,2,9,5,8,6};
auto result = std::minmax_element (foo.begin(),foo.end());
// print result:
std::cout << "min is " << *result.first;
std::cout << ", at position " << (result.first-foo.begin()) << '\n';
std::cout << "max is " << *result.second;
std::cout << ", at position " << (result.second-foo.begin()) << '\n';
The question is how can I use the same idea and go over my own vector and only check for y
of the points?
std::minmax_elements
, like many other algorithms, provides an overload that accepts a custom predicate:
template< class ForwardIt, class Compare > std::pair<ForwardIt,ForwardIt> minmax_element( ForwardIt first, ForwardIt last, Compare comp );
You can use that with a lambda expression to achieve what you want:
const auto result = std::minmax_element(foo.begin(), foo.end(),
[](const QPointF& a, const QPointF& b){ return a.y() < b.y(); });