gpt4 book ai didi

c++ - 使用算法头查找自定义数据类型的 minmax

转载 作者:太空宇宙 更新时间:2023-11-04 15:11:56 25 4
gpt4 key购买 nike

我有一个 vector QPointF我需要找到最小值和最大值 y值,因为我需要知道 vector 中数据的幅度是多少。

我使用 QPointF,但为了添加每个新元素,我总结了 x 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()));
}

因此我将有一个连续的波形...这很好用!但现在我需要找到波形的幅度,所以我需要找到最小值和最大值 y points 的值 vector 。

例如我需要一个函数来返回 min y和最大值 ystd::pair<float,float>我在算法标题中看到我们有类似的东西:

  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';

问题是我如何使用相同的想法并遍历我自己的 vector 并只检查 y的点数?

最佳答案

std::minmax_elements与许多其他算法一样,提供了一个接受自定义谓词的重载:

template< class ForwardIt, class Compare >
std::pair<ForwardIt,ForwardIt>
minmax_element( ForwardIt first, ForwardIt last, Compare comp );

您可以将其与lambda 表达式 一起使用以实现您想要的:

const auto result = std::minmax_element(foo.begin(), foo.end(), 
[](const QPointF& a, const QPointF& b){ return a.y() < b.y(); });

关于c++ - 使用算法头查找自定义数据类型的 minmax,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54804707/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com