![](/img/trans.png)
[英]What is the difference between std::stable_partition() and std::partition()?
[英]What is relative order and what does stable_partition do?
所以我得到了这个代码:
#include <vector>
#include <algorithm>
bool isEven(int x) {
return x % 2 == 0;
}
int main() {
std::vector<int> vec = {1,7,3,10,9,6};
std::stable_partition(vec.begin(), vec.end(), isEven);
}
现在我不明白stable_partition
和partition
之间的具体区别是什么。
所以我看了我的书,上面写着:
stable_partition 维护每个分区中元素的相对顺序
但我不明白,元素的相对顺序是什么?
这是否意味着与分区谓词不匹配的元素保持相同的顺序? 如果是,如何在std::partition
中更改它们?
提前致谢。
元素的相对顺序只是特定分区内的元素相对于彼此的顺序。
例如,在partition
之后
{1,7,3,10,9,6}
我们得到:
{6,10} {1,3,7,9} // one of the possible results
// ^^^^^^ ^^^^^^^^^ elements within partition can be in any order
所以不能保证保持相对顺序。 请注意,6 在 10 之前,而在 10 之后是在分区之前。
另一方面,如果你做一个stable_partition
,你会得到:
{10,6} {1,7,3,9} // only possible result
并且保证每个分区内的相对顺序保持不变。
相对顺序意味着相对于原始顺序,新的分区集将保持该顺序。 在您的示例中,这意味着
{1,7,3,10,9,6}
变得
{10,6,1,7,3,9}
由于偶数和赔率的顺序没有改变,只是它们在集合中的位置
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.