순열(permutation)은 서로 다른 n개의 원소에서 r개를 뽑아 한줄로 세우는 경우의 수를 표현할 수 있다
C++ STL을 사용하여 순열을 쉽게 표현할 수 있다.
헤더파일
#include<algoritm>
기본형
bool next_permutation(BidirectionalIterator first, BidirectionalIterator last);
bool next_permutation(BidirectionalIterator first, BidirectionalIterator last, Compare com);
● 인자 : 컨테이너(배열)의 시작과 끝 iterator
● true : 다음 순열이 존재하면 컨테이너의 원소들을 해당 순열로 바꾼 뒤 true 반환
● false : 다음 순열이 존재하지 않는다면 false 반환
● 비교함수 직접 작성 가능
규칙
● 컨테이너는 오름차순으로 정렬되어야 함
● 순열의 순서는 default로 오름차순으로 생성됨
● 컨테이너의 중복 원소는 제외하고 순열을 생성함
#include<iostream>
#include<algorithm>
#include<array>
using namespace std;
int main(void) {
array<int, 4> arr = { 1, 2, 3, 4 };
sort(arr.begin(), arr.end());
do {
for (auto element : arr)
cout << element << " ";
cout << endl;
} while (next_permutation(arr.begin(), arr.end()));
return 0;
}
'C++ > STL' 카테고리의 다른 글
Map (0) | 2024.03.19 |
---|---|
우선 순위 큐 (Priority_Queue) (0) | 2024.03.19 |