C++ 튜플 (Tuple)에 대하여
04 Mar 2020 | c++ programming effective함수형 프로그래밍에서는 어떤 상태가 변하지 않는다는 불변성이 주요 관심사인데, 튜플을 사용하면 코드에서 전역 상태를 제거할 수 있어 함수형 코드 작성에 도움이 된다.
사용 방법은 아래 예제에서 확인할 수 있다.
#include
using namespace std;
auto main() -> int {
// 두 가지의 방법으로 튜플을 초기화할 수 있다.
tuple<int, string, bool> t1(1, "Robert", true);
auto t2 = make_tuple(2, "Anna", false);
// t1 요소 출력
cout << "t1 elements: " << endl;
cout << get<0>(t1) << endl;
cout << get<1>(t1) << endl;
cout << get<2>(t1) << endl;
cout << endl;
// t2 요소 출력
cout << "t2 elements: " << endl;
cout << get<0>(t2) << endl;
cout << get<1>(t2) << endl;
cout << get<2>(t2) << endl;
cout << endl;
// tie(), 또다른 값 추출 방법
int i;
string s;
bool b;
tie(i,s,b) = t1;
cout << "tie(i,s,b) = t1" << endl;
cout << "i = " << i << endl;
cout << "s = " << s << endl;
cout << "b = " << b << endl;
cout << endl;
// 값을 ignore 하고싶은 경우?
tie(ignore,s,ignore) = t2;
cout << "s = " << s << endl;
return 0;
}