본문 바로가기

[ C/ C++ 프로그래밍 ]/[ STL ]

[ 혼연 정리 ] STL 알고리즘 - 6 [ 변경 알고리즘 ]


ㅇ  요소 재배치
 - 요소 재배치 함수들은 구간의 요소들을 특정한 다른 값으로 바꾸거나 요소끼리 교환함으로써 위치를 변경한다.

ㅇ replace()

void replace (FwdIt first, FwdIt last, const Type& Old, const Type& New);

  - first ~ last 사이의 Old 값을 찾아 new로 대처한다.
  - replace_if : 특정값이 아닌 특정 조건을 만족하는 값을 다른 값으로 변경
  - replace_copy : 복사버젼
  - replace_copy_if : 조건자를 취하는 복사함수

ㅇ reverse()

void reverse(BiIt first, BiIt last);

 - 구간의 모든 요소의 순서를 반대로 뒤집는다
 - reverse_copy : 복사 함수
-

ㅇ rotate()

void rotate(FwdIt first, FwdIt middle, FwdIt last);

 - first ~ last 구간을 middle을 기준으로 회전시킨다.

1 #include <iostream>
2 #include <vector>
3 #include <algorithm>
4
5 using namespace std;
6
7 template<typename C>
8 void dump(const char *desc, C c) 9 {
10     cout.width(12);cout << left << desc << "==> ";
11     copy(c.begin(),c.end(),ostream_iterator<typename C::value_type>(cout," "));
12     cout << endl;
13 }
14
15 void main()
16 {
17     const char *str="Notebook Computer";
18     vector<char> vc(&str[0],&str[strlen(str)]);
19
20     dump("원본",vc);
21     replace(vc.begin(),vc.end(),'o','a');
22     dump("replace",vc);
23     rotate(vc.begin(),vc.begin()+2,vc.end());
24     dump("rotate",vc);
25     reverse(vc.begin(),vc.end());
26     dump("reverse",vc);
27 }



ㅇ partition(), stable_ partition()
 - 일정한 조건을 기준으로 요소들을 좌우로 재배치한다

 BiIt partition(BiIt first, BiIt last, UniPred F);
 BiIt stable_partition(BiIt first, BiIt last, UniPred F);


- 단항 조건자 F : 구간내의 요소들을 인수로 전달받아 이 요소가 조건에 맞는지 아닌지를 판별한다.
 - partition함수 : F의 평가 결과에 따라 조건에 맞는 요소는 구간의 앞쪽으로, 그렇지 않으면 뒤쪽으로 이동시키며 뒤쪽 그룹의 시작 위치를 리턴
 - stable_ partition 함수 : 재배치후에도 요소들의 원래 순서가 유지되는 안정된 버전, 같은 그룹에 속하는 값들끼리라도 원래 앞쪽에 있었다면 재배치 후에도
     여전히 앞쪽에 배치 된다는 뜻, 안정성이 있는 대신 partition함수 보다 느리며 더 많은 메모리를 소모

1 #include <iostream>
2 #include <vector>
3 #include <algorithm>
4 #include <functional>
5
6 using namespace std;
7
8 template<typename C>
9 void dump(const char *desc, C c) 10 {
11     cout.width(12);cout << left << desc << "==> ";
12     copy(c.begin(),c.end(),ostream_iterator<typename C::value_type>(cout," "));
13     cout << endl;
14 }
15
16 void main()
17 {
18      int ari[]={3,1,4,1,5,9,2,6,5,3,5,8,9,7,9,3,2,3,8};
19      vector<int> vi(&ari[0],&ari[sizeof(ari)/sizeof(ari[0])]);
20
21      dump("원본",vi);
22      partition(vi.begin(),vi.end(),bind2nd(greater<int>(),5));
23      dump("partition",vi);
24
25      vector<int> ar2(&ari[0],&ari[sizeof(ari)/sizeof(ari[0])]);
26      stable_partition(ar2.begin(),ar2.end(),bind2nd(greater<int>(),5));
27      dump("stable",ar2);
28 }



ps : 출처 및 자세한 내용은  www.WinAPI.co.kr 참고