std::stable_partition() 和 std::partition() 有什么区别?

Moh*_*rma 3 c++ algorithm parameters partition

stable_partition(vect.begin(), vect.end(), [](int x) { return x % 2 == 0; });

partition(vect.begin(), vect.end(), [](int x) {
  return x % 2 == 0;
});
Run Code Online (Sandbox Code Playgroud)

上面的代码是为了解释两者之间的区别。

Ayx*_*xan 7

“稳定”意味着等效元素的顺序不会改变:

std::stable_partition来自cppreference.com

重新排序的元素以这样的方式,所有的元素的量,谓词范围[第一,最后一个)p返回true之前为其谓词的元素p返回false元素的相对顺序被保留。


dra*_*sht 6

解决这个问题的最好方法可能是举个例子。让我在这里抄袭cppreference 中的示例:

#include <iostream>
#include <algorithm>
#include <vector>

int main()
{
    std::vector<int> v{0, 0, 3, 0, 2, 4, 5, 0, 7};
    std::stable_partition(v.begin(), v.end(), [](int n){return n>0;});
    for (int n : v) {
        std::cout << n << ' ';
    }
    std::cout << '\n';
}
Run Code Online (Sandbox Code Playgroud)

运行此一个让你:3 2 4 5 7 0 0 0 0。3, 2, 4, 5, 7 就> 0谓词定义的关系而言是等价的,正如预期的那样,它们没有重新排序。

但是,如果更换stable_partition使用partition了同样的例子你:7 5 3 4 2 0 0 0 0。这次不能保证保持等效元素的顺序,显然它不是。