C++

[C++] tuple 사용법

soobinida 2023. 7. 11. 21:24

tuple은 서로 다른 데이터 유형일 수 있는 세 가지 이상의 값을 함께 저장할 때 사용된다.

note: #include <tuple> 헤더를 사용한다.

 

#include <iostream>
#include <tuple>
using namespace std;
  
int main()
{
    tuple<char, int, string> t;
    
    t = make_tuple('a', 65, "alphabet"); // make_tuple 함수 사용
    
    cout << "First Value: " << get<0>(t) << endl;
    cout << "Second Value: " << get<1>(t) << endl;
    cout << "Third Value: " << get<2>(t) << endl;

    return 0;
}

 

Output

First Value: a
Second Value: 65
Third Value: alphabet

 

tuple안에 저장된 값을 접근 할 때는 get<index>(tuple name) 형식이다.

 

 

 

또한, tie를 사용하여 tuple안에 저장된 값을 가져올 수 있다.

 

#include <iostream>
#include <tuple>
using namespace std;
  
int main()
{
    tuple<int, int, int> t;
    
    t = make_tuple(1, 2, 3); // make_tuple 함수 사용
    
    int a, b, c;
    tie(a, b, c) = t; // tie 사용
    
    cout << "First Value: " << a << endl;
    cout << "Second Value: " << b << endl;
    cout << "Third Value: " << c << endl;

    return 0;
}

 

Output

First Value: 1
Second Value: 2
Third Value: 3

'C++' 카테고리의 다른 글

[C++] pair 사용법  (0) 2023.07.11