본문 바로가기

프로그래밍 언어 노트/C++ | Modern C++

[Modern C++] Partition

    vector<int> v1 = { 1, 2, 4, 5, 3, 6, 8, 5, 7, 9 };
    vector<int> v2 = { 1, 2, 4, 5, 3, 6, 8, 5, 7, 9 };


    auto lambda = [](int x) { return x % 2 == 1; };
    auto p = partition(v1.begin(), v1.end(), lambda);
    auto s = stable_partition(v2.begin(), v2.end(), lambda);

    for (auto i = v1.begin(); i < v1.end(); i++)
    {
        cout << *i << "\t";

        if (p == i)
        {
            cout << endl;
        }
    }
    cout << endl;

    for (auto i = v2.begin(); i < v2.end(); i++)
    {
        cout << *i << "\t";

        if (s == i)
        {
            cout << endl;
        }
    }
    cout << endl;

    cout << "is partitioned?: " << is_partitioned(v1.begin(), v1.end(), lambda) << endl;
    cout << "is partitioned?: " << is_partitioned(v2.begin(), v2.end(), lambda) << endl;

partition 자체는 모던은 아니고 is partitioned 가 11에서 추가되었다.

partition 은 3번째의 조건에따라 받은 배열을 재배치 하고 분할된 위치의 이터레이터를 반환.

statble 은 이때 기존의 순서를 보장해준다.

is partitioned 는 이 조건에 따라 분할됬는지 확인하는 함수이다.

728x90