0

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?

2 Answers 2

4

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(); });
Sign up to request clarification or add additional context in comments.

Comments

3

There is an overload which takes comparison predicate that you might use:

std::vector<QPointF> points /* = .. */;

std::minmax_element (points.begin(), points.end(),
                     [](const QPointF& lhs, const QPointF& rhs){
                         return lhs.y() < rhs.y();
                     });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.