transform()

김민수·2025년 1월 8일

C++

목록 보기
40/68

컨테이너의 요소에 대해 지정된 연산을 적용하고, 결과를 저장하는 데 사용되는 알고리즘 함수다.


1. 매개변수

#include <algorithm>

std::transform(입력_시작, 입력_끝, 결과_시작, 함수_또는_람다);
  • 입력_시작: 변환을 시작할 첫 번째 요소의 반복자
  • 입력_끝: 변환을 종료할 위치(포함되지 않음)
  • 결과_시작: 변환된 결과를 저장할 위치의 반복자
  • 함수 또는 람다: 각 요소에 적용할 변환 함수


2. 반환값

  • 변환이 끝난 위치의 반복자


3. 기본 예제 (벡터 요소에 대한 제곱 연산)

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

int main() {
    std::vector<int> vec = {1, 2, 3, 4, 5};
    std::vector<int> result(vec.size());

    // 각 요소에 제곱을 적용하여 결과에 저장
    std::transform(vec.begin(), vec.end(), result.begin(), [](int x) {
        return x * x;
    });

    // 결과 출력
    for (int num : result) {
        std::cout << num << " ";
    }

    return 0;
}


4. 두 개의 컨테이너 요소를 더하는 예제

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

int main() {
    std::vector<int> vec1 = {1, 2, 3, 4, 5};
    std::vector<int> vec2 = {10, 20, 30, 40, 50};
    std::vector<int> result(vec1.size());

    // vec1과 vec2의 요소를 더하여 result에 저장
    std::transform(vec1.begin(), vec1.end(), vec2.begin(), result.begin(), [](int a, int b) {
        return a + b;
    });

    // 결과 출력
    for (int num : result) {
        std::cout << num << " ";
    }

    return 0;
}


5. 문자열 대문자로 변환 예제

#include <iostream>
#include <string>
#include <algorithm>
#include <cctype> // std::toupper

int main() {
    std::string str = "hello world";
    std::string result(str.size(), ' ');

    // 각 문자에 대해 std::toupper를 적용하여 결과에 저장
    std::transform(str.begin(), str.end(), result.begin(), [](char c) {
        return std::toupper(c);
    });

    // 결과 출력
    std::cout << "Original: " << str << "\n";
    std::cout << "Transformed: " << result << "\n";

    return 0;
}


6. 배열 요소에 대해 함수 적용 예제

#include <iostream>
#include <algorithm>

int square(int x) {
    return x * x;
}

int main() {
    int arr[] = {1, 2, 3, 4, 5};
    int result[5];

    // 배열 요소에 대해 square 함수 적용
    std::transform(arr, arr + 5, result, square);

    // 결과 출력
    for (int num : result) {
        std::cout << num << " ";
    }

    return 0;
}


7. 사용자 정의 구조체에 대해 변환 예제

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

struct Person {
    std::string name;
    int age;
};

struct PersonSummary {
    std::string name;
    int ageCategory;
};

int categorizeAge(int age) {
    return (age < 18) ? 1 : (age < 60) ? 2 : 3; // 1: 청소년, 2: 성인, 3: 노인
}

int main() {
    std::vector<Person> people = {{"Alice", 25}, {"Bob", 15}, {"Charlie", 65}};
    std::vector<PersonSummary> result(people.size());

    // 사람의 나이를 카테고리로 변환하여 저장
    std::transform(people.begin(), people.end(), result.begin(), [](const Person &p) {
        return PersonSummary{p.name, categorizeAge(p.age)};
    });

    // 결과 출력
    for (const auto &summary : result) {
        std::cout << "Name: " << summary.name << ", Age Category: " << summary.ageCategory << "\n";
    }

    return 0;
}
profile
안녕하세요

0개의 댓글