Programming/c++

[c++] std::partition_point

owls 2022. 12. 26. 14:04
728x90

1.함수 헤더 파일

#include <algorithm>

2.함수 원형

template<class ForwardIterator, class UnaryPredicate>
ForwardIterator partition_point(
    ForwardIterator first,
    ForwardIterator last,
    UnaryPredicate pred);

조건을 충족하지 않는 지정된 범위의 첫 번째 요소를 반환합니다. 조건을 충족하는 요소가 그렇지 않은 요소 앞에 오도록 요소가 정렬됩니다.

 

3.return 값(반환 값)

반복자를 반환합니다.

테스트한 조건을 충족하지 않는 첫 번째 요소의 반복자,

반환하는 pred에서 last 반복자까지 찾을 수 없는 경우

 

4.예제

std::vector<int> vec2 {2, 4, 6, 8, 10, 1, 3, 5, 7, 9};

  auto point = std::partition_point(vec2.begin(), vec2.end(), [](int i){
        return (i % 2 == 0);  
    });
    
int index =  point - vec2.begin();  // std::distance(vec2.begin(), point);   

std::vector<int> odd;
odd.assign(vec2.begin(), point);
index : 5
odd = [2,4,6,8,10]

사용자 지정 함수가 false가 되는 첫번째 반복자를 point 변수에 저장합니다.

int형으로 index를 구하기 위해  (point 변수 반복자 - begin() )를 연산합니다.

 

사용자 지정 함수 pred는 짝수는 true, 홀수는 false 를 반환하는 함수입니다.

홀수가 되는 첫번째 요소의 위치는 5번째 입니다.

std::vector<int> vec2 {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

auto point = std::partition_point(vec2.begin(), vec2.end(), [](int i){
        return (i % 2 == 1);  
    });
   
  int index = point - vec2.begin();
index : 5

pred는 홀수 true, 짝수 false 를 리턴하는 사용자 지정 함수입니다.

pred가 false가 나오는 첫번째 요소 index로 5가 나왔습니다.

 

std::partition_point 함수는 std::stable_partition 함수를 같이 사용해야 하는 것 같습니다.

std::stable_partition 내용은 아래 포스팅을 참고하면 됩니다~
 

[c++] std::stable_partition

1.함수 헤더 파일 #include 2.함수 원형 template BidirectionalIterator stable_partition( BidirectionalIterator first, BidirectionalIterator last, UnaryPredicate pred ); template BidirectionalIterator stable_partition( ExecutionPolicy&& exec, Bidire

code-space.tistory.com

 

 

 

728x90