C++ tuple 핵심 요약 | "튜플" 완벽 가이드

C++ tuple 핵심 요약 | "튜플" 완벽 가이드

이 글의 핵심

C++ tuple에 대해 정리한 개발 블로그 글입니다. #include <tuple> using namespace std;

기본 사용법

#include <tuple>
using namespace std;

int main() {
    // 생성
    tuple<int, double, string> t1(42, 3.14, "Hello");
    
    // make_tuple
    auto t2 = make_tuple(42, 3.14, "Hello");
    
    // 접근
    cout << get<0>(t1) << endl;  // 42
    cout << get<1>(t1) << endl;  // 3.14
    cout << get<2>(t1) << endl;  // Hello
}

구조적 바인딩 (C++17)

auto t = make_tuple(42, 3.14, "Hello");

// 언팩
auto [i, d, s] = t;

cout << i << endl;  // 42
cout << d << endl;  // 3.14
cout << s << endl;  // Hello

tie

int i;
double d;
string s;

auto t = make_tuple(42, 3.14, "Hello");

// 기존 변수에 언팩
tie(i, d, s) = t;

cout << i << endl;  // 42

// 일부 무시
tie(i, ignore, s) = t;

실전 예시

예시 1: 다중 반환값

tuple<int, int, int> divmod(int a, int b) {
    return {a / b, a % b, a};
}

int main() {
    auto [quotient, remainder, original] = divmod(17, 5);
    
    cout << original << " / 5 = " << quotient 
         << " ... " << remainder << endl;
    // 17 / 5 = 3 ... 2
}

예시 2: 함수 결과 캐싱

#include <map>

map<int, tuple<int, int>> cache;

tuple<int, int> fibonacci(int n) {
    if (n <= 1) {
        return {n, n};
    }
    
    if (cache.find(n) != cache.end()) {
        return cache[n];
    }
    
    auto [a, b] = fibonacci(n - 1);
    auto result = make_tuple(b, a + b);
    cache[n] = result;
    
    return result;
}

int main() {
    for (int i = 0; i < 10; i++) {
        auto [curr, next] = fibonacci(i);
        cout << curr << " ";
    }
    // 0 1 1 2 3 5 8 13 21 34
}

예시 3: 데이터베이스 행

using Row = tuple<int, string, double>;

vector<Row> queryDatabase() {
    return {
        {1, "Alice", 90.5},
        {2, "Bob", 85.0},
        {3, "Charlie", 95.5}
    };
}

int main() {
    auto rows = queryDatabase();
    
    for (const auto& [id, name, score] : rows) {
        cout << id << ": " << name << " (" << score << ")" << endl;
    }
}

예시 4: 좌표 시스템

using Point2D = tuple<double, double>;
using Point3D = tuple<double, double, double>;

Point2D add2D(Point2D p1, Point2D p2) {
    auto [x1, y1] = p1;
    auto [x2, y2] = p2;
    return {x1 + x2, y1 + y2};
}

double distance2D(Point2D p1, Point2D p2) {
    auto [x1, y1] = p1;
    auto [x2, y2] = p2;
    return sqrt((x2-x1)*(x2-x1) + (y2-y1)*(y2-y1));
}

int main() {
    Point2D p1 = {0, 0};
    Point2D p2 = {3, 4};
    
    auto sum = add2D(p1, p2);
    auto [x, y] = sum;
    cout << "합: (" << x << ", " << y << ")" << endl;
    
    cout << "거리: " << distance2D(p1, p2) << endl;  // 5
}

tuple_cat

auto t1 = make_tuple(1, 2);
auto t2 = make_tuple(3.14, "Hello");

// 튜플 결합
auto combined = tuple_cat(t1, t2);
// tuple<int, int, double, string>

auto [a, b, c, d] = combined;
cout << a << ", " << b << ", " << c << ", " << d << endl;

tuple vs pair

// pair (2개)
pair<int, string> p = {1, "Alice"};
cout << p.first << ", " << p.second << endl;

// tuple (N개)
tuple<int, string, double> t = {1, "Alice", 90.5};
cout << get<0>(t) << ", " << get<1>(t) << ", " << get<2>(t) << endl;

자주 발생하는 문제

문제 1: 인덱스 범위

// ❌ 범위 초과
auto t = make_tuple(1, 2, 3);
// cout << get<3>(t) << endl;  // 컴파일 에러

// ✅ 올바른 인덱스
cout << get<0>(t) << endl;
cout << get<1>(t) << endl;
cout << get<2>(t) << endl;

문제 2: 타입 추론

// ❌ 타입 추론 실패
auto t = make_tuple(1, 2, 3);
// int x = get<int>(t);  // 에러: 인덱스 필요

// ✅ 인덱스 사용
int x = get<0>(t);

문제 3: 참조 저장

int x = 10;

// ❌ 복사
auto t1 = make_tuple(x);
get<0>(t1) = 20;
cout << x << endl;  // 10 (변경 안됨)

// ✅ 참조
auto t2 = make_tuple(ref(x));
get<0>(t2) = 20;
cout << x << endl;  // 20 (변경됨)

tuple 크기

auto t = make_tuple(1, 2.0, "three");

// 크기
constexpr size_t size = tuple_size<decltype(t)>::value;
cout << size << endl;  // 3

// 타입
using T0 = tuple_element<0, decltype(t)>::type;  // int
using T1 = tuple_element<1, decltype(t)>::type;  // double
using T2 = tuple_element<2, decltype(t)>::type;  // const char*

FAQ

Q1: tuple은 언제 사용하나요?

A:

  • 다중 반환값
  • 임시 데이터 그룹
  • 제네릭 프로그래밍

Q2: tuple vs struct?

A:

  • tuple: 간단, 임시
  • struct: 명확한 이름, 가독성

Q3: 성능 오버헤드는?

A: 없습니다. 컴파일 타임에 최적화됩니다.

Q4: tuple vs pair?

A: pair는 2개 전용. 3개 이상이면 tuple.

Q5: tuple 순회는?

A: apply나 템플릿 메타프로그래밍 필요.

Q6: tuple 학습 리소스는?

A:

  • cppreference.com
  • “The C++ Standard Library”
  • “Effective Modern C++“

같이 보면 좋은 글 (내부 링크)

이 주제와 연결되는 다른 글입니다.

  • C++ tuple | “튜플” 가이드
  • C++ 범위 기반 for문과 구조화된 바인딩 | 모던 C++ 반복문
  • C++ User-Defined Literals | “사용자 정의 리터럴” 가이드

관련 글

  • C++ tuple 상세 가이드 |
  • C++ async & launch |
  • C++ Atomic Operations |
  • C++ Attributes |
  • C++ auto 키워드 |