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),predicate); auto iter = std::partition_point(std::begin(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::cout << std::endl;这段代码会相对于平均温度对 temperatures 中的元素进行分区,并通过调用 partition_point() 找到这个序列的分区点。这个分区点是第一个分区的结束迭代器,它被保存在 iter 中。所以 [std::begin(temperatures),iter) 对应的就是第一个分区中的元素,[iter,std::end(temperatures)) 包含的是第二个分区中的元素。这里使用两次 copy() 算法来输出分区,输出内容如下:
Elements in the first partition: 31 28 32 29 40 41 44
Elements in the second partition: 65 75 56 48 50
在对 temperatures 使用 partition_point() 算法之前,可以先用它来验证这个序列:
if(std::is_partitioned(std::begin(temperatures),[average](double t) { return t < average; })) { auto iter = std::partition_point(std::begin(temperatures),[average](double t) { return t < average; }); std::cout << "Elements in the first partition: "; std::copy(std::begin(temperatures)," " }); std::cout << "\nElements in the second partition: "; std::copy(iter," "}); std::cout << std::endl; } else std::cout << "Range is not partitioned." << std::endl;只有在 is_partitioned() 返回 true 时,这段代码才会执行。如果 if 语句为 true,iter 变量会指向分区点。如果想在后面继续使用 iter,可以按如下方式在 if 语句之前定义它:
std::vector<double>::iterator iter;在所有容器类型的模板中都定义了这样的迭代器类型别名,它们使迭代器变得可以使用。它对应于这个容器类型的成员函数 begin() 和 end() 所返回的迭代器类型。