728x90
1. 개요
오늘은 C++의 tuple에 대해서 공부하겠습니다.
2. tuple?
tuple은 C++11에 나온 타입중 하나 입니다.
tuple(튜플)은 서로 다른 타입 즉 int double boolean등 두개 이상의 타입을 하나의 변수의 묶을수있는 기능을 가지고 있습니다.
보통 pair 키워드는 두 개만 저장할수있는 반면 tuple은 두 개 이상 저장이 가능합니다.
아래의 예시를 보겠습니다.
#include<iostream>
#include<any>
#include<tuple>
using namespace std;
int main()
{
tuple<int, int, bool> tu;
tu = make_tuple(5, 5, false);
cout << get<0>(tu) << ' ' << get<1>(tu) << ' ' << get<2>(tu);
return 0;
}
이런 형식으로 사용할수 있습니다.
pair와 다르게 tuple을 불러오는 방법은 get을 통해 불러올수 있습니다.
또한 tie를 통해 각 변수에 tuple 안에있는 데이터를 넣어줄수있습니다.
왼쪽부터 0 1 2 번째에 값을 넣어주며 tie함수를 통해 간편하고, 간결하게 만들수있습니다.
#include<iostream>
#include<any>
#include<tuple>
using namespace std;
int main()
{
tuple<int, int, bool> tu;
tu = make_tuple(5, 5, false);
int x, y;
bool a;
tie(x, y, a) = tu;
cout << x << ' ' << y << ' ' << a;
return 0;
}
또한, pair도 가능
#include<iostream>
#include<any>
#include<tuple>
using namespace std;
int main()
{
tuple<int, int, bool> tu;
tu = make_tuple(5, 5, false);
int x, y;
bool a;
pair<int, int> pa = make_pair(5,5);
tie(x,y ) = pa;
cout << x << ' ' << y;
return 0;
}
#include<iostream>
#include<any>
#include<tuple>
using namespace std;
int main()
{
tuple<int, int, bool, double, string> tu;
tu = make_tuple(5, 5, false, 3.14, "나는 빡빡이다.");
int x, y;
bool b;
double d;
string s;
tie(x, y, b, d, s) = tu;
cout << x << ' ' << y << ' ' << b << ' ' << d << ' ' << s;
return 0;
}
5개의 튜플
'개발자 면접 공부 > C-C++' 카테고리의 다른 글
C++ 17 variant (0) | 2023.09.19 |
---|---|
C++ 17 구조적 바인딩 (2) | 2023.09.14 |
함수에 const 위치에 따른 결과 (0) | 2023.09.09 |
가변길이 템플릿 (0) | 2023.09.04 |
구조체, 클래스 패딩 바이트 (2) | 2023.08.28 |