[C++]튜플

강동현·2023년 12월 17일

Unreal Engine/C++

목록 보기
1/2

튜플(tuple)

1. 튜플(tuple)이란?

  • 사물의 유한한 순서를 뜻함
  • 두 개 이상의 순서대로 정렬된 서로 다른 값의 모임
  • 예시: (a, b, c, d, e, ..., z)

2. 튜플(tuple) 선언 방식

  • <> 안에 원하는 데이터 형을 나열
  • 반환 값이 두개 이상일 경우 사용 시, 효과적
  • 반환 값이 몇개던지 전달 가능
  • #include <tuple> 필요
//튜플 사용 시 선언 필수
#include <tuple>
//변수 선언 + uniform 초기화를 사용한 튜플 선언
std::tuple<int, char, string> tuple(10, 'c', "string");
//make_tuple을 활용한 튜플 초기화
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';//10
  	cout << get<1>(tuple) << '\n';//c
  	cout << get<2>(tuple) << '\n';//string
  	get<0>(tuple) = 20;//20
  	get<1>(tuple) = 'a';//20
  	get<2>(tuple) = "str";//20
}

4. 튜플(tuple) 원소 분해

  • tie() 함수 or []를 통해 튜플 원소 분해
//1. tie를 활용한 원소 분해
tuple<int, char, string> tuple = make_tuple(10, 'c', "string");
in2 x[]를 활용한 원소 분해(C++17 부터 사용)
char y;
string z;
std::tie(x, y, z) = tuple;
//2. []를 활용한 원소 분해(C++17 부터 사용)
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);
profile
GAME DESIGN & CLIENT PROGRAMMING

0개의 댓글