algorithm_partition

algorithm_partition (파티셔닝)

std::partition는 대상 범위의 요소들을 술어 p를 기준으로 재배열해서, p를 만족하는 요소들이 그렇지 않은 요소들보다 앞에 오게 해요.

출처: cppreference

본문

std::partition는 대상 범위 [first, last)의 요소 e를 표현식 bool(p(e))에 대해 파티셔닝해요: p를 만족하는 모든 요소가 그렇지 않은 모든 요소보다 앞에 와요. <algorithm> 헤더에 정의되어 있어요.

template< class ForwardIt, class UnaryPred >
ForwardIt partition( ForwardIt first, ForwardIt last, UnaryPred p );

병렬 실행 정책을 받는 오버로드도 있어요.

반환값 (Return value)

파티션 지점을 가리키는 반복자예요. 즉 첫 번째 부분 범위의 끝(past-the-end)으로, p를 만족하지 않는 첫 번째 요소를 가리켜요 (만약 모든 요소가 p를 만족하면 last).

복잡도 (Complexity)

Nstd::distance(first, last)라고 하면 std::partition𝓞(N)번의 스왑이 필요하고, ForwardItBidirectionalIterator라면 𝓞(N)번의 스왑, 그 외엔 𝓞(N·log N)번의 스왑이 필요해요. 그리고 정확히 N번의 p 적용이 필요해요.

예제 (Example)

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

int main()
{
    std::vector<int> v{1, 2, 3, 4, 5, 6, 7, 8, 9};
    auto it = std::partition(v.begin(), v.end(),
                             [](int x) { return x % 2 == 0; });
    for (auto e = v.begin(); e != it; ++e) std::cout << *e << ' ';
    std::cout << "| ";
    for (auto e = it; e != v.end(); ++e) std::cout << *e << ' ';
    std::cout << '\n';
}

출력 예:

8 2 6 4 | 5 3 7 1 9

더 알아보기 (Learn more)

cppreference