관리 메뉴

Kim's Programming

Algorithm - partition() 본문

STL - Algorithm/Algorithm - Partitions

Algorithm - partition()

Programmer. 2017. 7. 10. 23:08

원형)


1
2
3
4
//기본형
template <class ForwardIterator, class UnaryPredicate>
  ForwardIterator partition (ForwardIterator first,
                             ForwardIterator last, UnaryPredicate pred);
cs



의미)


리턴된 [Iterator first, Iterator last) 사이에 있는 데이터들을 pred 함수를 이용하여 true를 리턴한 값과 false를 리턴한 값으로 재정렬 합니다.



소스)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include<iostream>
#include<algorithm>
#include<vector>
 
void Print(const std::vector<int>& target)
{
    for (std::vector<int>::const_iterator iterPos = target.begin(); iterPos != target.cend(); iterPos++)
        std::cout << *iterPos << ' ';
    std::cout << std::endl;
}
 
bool isEven(int val)
{
    return val % == 0;
}
 
void main()
{
    std::vector<int> vector = { 10,5,2,4,9,3,7,};
    std::vector<int>::iterator iter;
 
    iter = std::partition(vector.begin(), vector.end(), isEven);
 
    std::cout << "odd element---> ";
    for (std::vector<int>::iterator iterPos = vector.begin(); iterPos != iter; ++iterPos)
        std::cout << *iterPos << " ";
    std::cout << std::endl;
 
    std::cout << "even element---> ";
    for (std::vector<int>::iterator iterPos = iter; iterPos  != vector.end(); ++iterPos)
        std::cout << *iterPos << " ";
    std::cout << std::endl;
    Print(vector);
}
cs



리턴값)


2번째 그룹(pred 함수가 false를 리턴한 값들)의 첫번째 원소를 가리키는 Iterator를 리턴합니다. 이 그룹이 비어있다면 Iterator last를 리턴합니다. 



결과)




'STL - Algorithm > Algorithm - Partitions' 카테고리의 다른 글

Algorithm - partition_point()  (0) 2017.07.11
Algorithm - partition_copy()  (0) 2017.07.11
Algorithm - stable_partition()  (0) 2017.07.11
Algorithm - is_partitioned()  (0) 2017.07.10