next_permutation

next_permutation (다음 순열)

범위를 사전순으로 다음 순열로 재배열하는 알고리즘이에요. <algorithm> 헤더에 있어요.

출처: cppreference

본문

next_permutation은 범위 [first, last)를 사전순으로 다음 순열로 바꿔요.

template< class BidirIt >
bool next_permutation( BidirIt first, BidirIt last );   // (1)

비교기 버전도 있어요.

template< class BidirIt, class Compare >
bool next_permutation( BidirIt first, BidirIt last, Compare comp );   // (2)
  • 반환 값: 다음 순열로 성공적으로 변환되면 true. 이미 마지막(가장 큰) 순열이어서 맨 앞(첫) 순열로 되돌렸다면 false.
std::vector<int> v{1, 2, 3};
do {
    for (int x : v) std::cout << x << ' ';
    std::cout << '\n';
} while (std::next_permutation(v.begin(), v.end()));
// 123, 132, 213, 231, 312, 321

모든 순열을 사전순으로 나열해 각각 처리할 때 쓰는 전형적인 패턴이에요. prev_permutation이 이전 순열로 가는 반대 연산이에요.

더 알아보기 (Learn more)

cppreference