함수 객체는 통상 ()연산자 하나만 정의하고 그나마도 동작이 간단해 길이가 아주 짧다.,
그래서 STL은 자주 사용할만한 연산에 대해 미리 함수 객체를 정의하고 있다. ==> 별다른 정의 없이 그냥 사용하면 된다.
- plus
대표적으로 가장 간단한 함수 객체
1 struct plus : public binary_function<T, T, T> {
2 T operator()(const T& x, const T& y) const { return (x+y); }
3 };
더할 피연산자의 타입 T를 인수로 받아들이는 클래스 탬플릿이다.
예 제 : plus
1 #include <iostream>
2 #include <functional>
3
4 using namespace std;
5
6 void main()
7 {
8 int nNum1 , nNum2 ;
9 int nSum;
10 printf("다음int형두수를입력하시오\n");
11 scanf("%d %d", &nNum1, &nNum2);
12
13 nSum = plus<int>()(nNum1, nNum2);
14 /* plus<int>()는디폴트생성자호출문이며임시객체를생성한다.
15 임시로선언된객체에인수값nNum1, nNum2를넘겨준다.
16 nSum = plus<int>()(nNum1, nNum2); 를풀어쓰면다음2줄과같다.
17 puls<int> P;
18 nSum = P( nNum1, nNum2 ) */
19
20 printf("합: %d\n", nSum);
21 }
- sort
정렬 순서를 원하는데로 지정할 수 있다.
1 void sort(RanIt first, RanIt last, BinPred F);
F : 비교할 두 요소를 전달받아 비교 결과를 bool형으로 리턴하는 함수 객체
예 제 : sortdesc
1 #include <iostream>
2 #include <string>
3 #include <vector>
4 #include <algorithm>
5 #include <functional>
6 using namespace std;
7
8 void main()
9 {
10 string names[]={"STL","MFC","owl","html","pascal","Ada",
11 "Delphi","C/C++","Python","basic"};
12
13 vector<string> vs(&names[0], &names[10]);
14
15 sort(vs.begin(), vs.end());
16
17 cout << " /* sort(vs.begin(), vs.end())의로정렬한결과 */" << endl;
18 vector<string>::iterator it;
19 for ( it = vs.begin() ; it != vs.end() ; it++ )
20 {
21 cout << *it << endl;
22 }
23
24 cout << endl << endl;
25 sort(vs.begin(), vs.end(), greater<string>());
26 cout << "/* sort(vs.begin(), vs.end(), greater<string>())으러정렬한결과 */" << endl;
27 for ( it = vs.begin() ; it != vs.end() ; it++ )
28 {
29 cout << *it << endl;
30 }
31 }
- 함수 객체 종류
ps : 자세한 내용은 www.WinAPI.co.kr 참고
'[ C/ C++ 프로그래밍 ] > [ STL ]' 카테고리의 다른 글
[ 혼연 정리 ] 함수객체- 5 [어뎁터 ] (1) | 2010.06.24 |
---|---|
[ 혼연 정리 ] 함수객체- 4 [함수 객체의 종류] (0) | 2010.06.24 |
[ 혼연 정리 ] 함수객체- 2 [알고리즘의 변형] (2) | 2010.06.24 |
[ 혼연 정리 ] 함수객체- 1 [함수객체] (0) | 2010.06.24 |
[ 혼연 정리 ] STL 개요 - 4 [알고리즘] (1) | 2010.05.31 |