[C++] transform 함수의 활용

wansuper·2024년 1월 1일
0

CodingTest

목록 보기
25/34
  1. algorithm을 include한다.

    #include <algorithm>
  2. 원형 - 단항 함수형:

    template <class InputIt, class OutputIt, class UnaryOperation>
    OutputIt transform(InputIt first, InputIt last, 
    				   OutputIt d_first, UnaryOperation unary_op); 
    • first, last : transform 함수를 적용할 원소들을 가리키는 범위
    • d_first : 결과를 저장할 범위 (first와 동일해도 됨. 이 경우, 기존 데이터를 덮어쓰게 됨)
    • unary_op : 원소들을 변환할 함수
    • 의미: first부터 last 전까지 범위의 원소에 unary_op를 수행하고, 그 결과를 d_first에 저장한다.
  3. 원형 - 이항 함수형:

    template <class InputIt1, class InputIt2, class OutputIt, class BinaryOperation>
    OutputIt transform(InputItr1 first1, InputItr1 last1, InputItr2 first2, 
    				   OutputIt d_first, BinaryOperation binary_op);
    • first1, last1 : transform 함수를 적용할 첫 번째 원소들을 가리키는 범위
    • first2 : transform 함수를 적용할 두 번째 원소들의 시작점
    • d_first : 결과를 저장할 범위 (first1, first2와 동일해도 됨. 이 경우, 기존 데이터를 덮어쓰게 됨)
    • binary_op : 원소들을 변환할 함수. 2개의 parameter를 가짐

예시

#include <algorithm>
#include <iostream>
#include <vector>

using namespace std;

//binary_op 
int twice(int n) {    
    return n*2;
} 

int main(){	
    vector<int> vec = {1, 2, 3, 4, 5};   
    
    //before transform 출력  
    for(int i = 0; i < vec.size(); i++){    
    	cout << vec[i];    
    }   
    
    cout << endl;     
    transform(vec.begin(), vec.end(), vec.begin(), twice);     
    
    //after transform 출력   
    for(int i = 0; i < vec.size(); i++){    
    	cout << vec[i];    
    }  
    
    return 0;
}

// 실행 결과: 1, 2, 3, 4, 5
//   	    1, 4, 9, 16, 25
int main(){	
    string str = "Hello World";
    
    //before transform 출력  
    cout << str << endl;     
    
    transform(str.begin(), str.end(), str.begin(), ::toupper);
    
    //after transform 출력   
    cout << str << endl;  
    
    return 0;
}
// 실행 결과: Hello World
// 			 HELLO WORLD

출처: https://artist-developer.tistory.com/28 [개발자 김모씨의 성장 일기:티스토리]

profile
🚗 Autonomous Vehicle 🖥️ Study Alone

0개의 댓글