튜플(tuple)
1. 튜플(tuple)이란?
- 사물의 유한한 순서를 뜻함
- 두 개 이상의 순서대로 정렬된 서로 다른 값의 모임
- 예시: (a, b, c, d, e, ..., z)
2. 튜플(tuple) 선언 방식
- <> 안에 원하는 데이터 형을 나열
- 반환 값이 두개 이상일 경우 사용 시, 효과적
- 반환 값이 몇개던지 전달 가능
- #include <tuple> 필요
#include <tuple>
std::tuple<int, char, string> tuple(10, 'c', "string");
tuple<int, char, string> tuple;
tuple = make_tuple(10, 'c', "string");
3. 튜플(tuple) 원소 접근 & 수정
- get<> 함수를 통해 접근
- <> 안에 자료형이 아닌 접근하고 싶은 튜플 원소의 index가 들어감
- () 안에 접근할 튜플의 이름을 적어줌
#include <bits/stdc++.h>
using namespace std;
int main(){
tuple<int, char, string> tuple = make_tuple(10, 'c', "string");
cout << get<0>(tuple) << '\n';
cout << get<1>(tuple) << '\n';
cout << get<2>(tuple) << '\n';
get<0>(tuple) = 20;
get<1>(tuple) = 'a';
get<2>(tuple) = "str";
}
4. 튜플(tuple) 원소 분해
- tie() 함수 or []를 통해 튜플 원소 분해
tuple<int, char, string> tuple = make_tuple(10, 'c', "string");
in2 x[]를 활용한 원소 분해(C++17 부터 사용)
char y;
string z;
std::tie(x, y, z) = tuple;
auto [x, y, z] = tuple;
5. 튜플(tuple) 원소 교환
- void swap(tuple1, tuple2) 함수
tuple<int, char, string> tuple1 = make_tuple(10, 'c', "string");
tuple<int, char, string> tuple2 = make_tuple(-10, 'a', "-string");
std::swap(tuple1, tuple2);
6. 튜플(tuple) 붙이기
- tuple tuple_cat(tuple1, tuple2) 함수
tuple<int, char, string> tuple1 = make_tuple(10, 'c', "string");
tuple<int, char, string> tuple2 = make_tuple(-10, 'a', "-string");
tuple<int, char, string, int, char, string> tuple3 = tuple_cat(tuple1, tuple2);
std::swap(tuple1, tuple2);