STL partition_point分割算法

本文介绍了C++ STL中的partition_point算法,该算法用于找到序列中某个分区的结束迭代器。通过提供一个谓词,我们可以查找序列的第一个分区的边界。在使用此算法之前,应确保序列已经被正确分区,这可以通过is_partitioned()函数检查。示例代码展示了如何使用这些算法处理序列,例如根据平均温度对温度数组进行分区。
摘要由CSDN通过智能技术生成

可以用 partition_point() 算法来获取分区序列中第一个分区的结束迭代器,它的前两个参数定义检查范围的正向迭代器,最后一个参数是用来对序列进行分区的谓词。我们通常不知道每个分区中元素的个数,这个算法使我们能够访问和提取这些分区中的元素。例如:

std::vector<double> temperatures {65, 75, 56, 48, 31, 28, 32, 29, 40, 41, 44, 50};
auto average = std::accumulate(std::begin(temperatures),std::end(temperatures), 0.0)/ temperatures.size();
auto predicate = [average](double t) { return t < average; };
std::stable_partition(std::begin(temperatures), std::end(temperatures), predicate);
auto iter = std::partition_point(std::begin(temperatures),std::end(temperatures), predicate);
std::cout << "Elements in the first partition: ";
std::copy(std::begin(temperatures), iter,std::ostream_iterator<double>{std::cout, " "});
std::cout << "\nElements in the second partition: ";std::copy(iter, std::end(temperatures),std::ostream_iterator<double>{std::c
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值