1. pair & tuple
#include <iostream>
#include <utility> // for pair
#include <tuple> // for tuple, tie
using namespace std;
pair<int, int> pi;
tuple<int, int, int> tl;
int a, b, c, d, e, f;
int main(){
pi = {1, 2};
tl = make_tuple(1,2,3);
tie(a,b) = pi;
cout << a<<" : "<< b << endl;
tie(a,b,c) = tl;
cout << a << " : " << b << " : " << c << endl;
d = pi.first;
e = pi.second;
cout << d << " : " << e << endl;
d = get<0>(tl);
e = get<1>(tl);
f = get<2>(tl);
cout << d << " : " << e << " : " << f << endl;
return 0;
}
/*
1 : 2
1 : 2 : 3
1 : 2
1 : 2 : 3
*/
Code language: PHP (php)
pair와 tuple은 서로 다른 데이터 타입의 값들을 하나의 변수에 저장할 때 매우 유용하다.
pair는 first와 second 라는 멤버변수를 가지는 클래스로 두 가지 값을 묶어서 저장할 수 있습니다.tuple은 세가지 이상의 값 묶어서 저장할 때 사용한다.
가. 선언
pair<int, int> pi;
pi = make_pair(1, 2);
//또는
pi = {1, 2};
Code language: HTML, XML (xml)
tuple<int, int, int> tl;
tl = make_tuple(1,2,3);
//또는
tuple<int, int, int> t1(1,2,3);
Code language: HTML, XML (xml)
make_pair와 make_tuple이 기억하기 쉬운 것 같다.
나. 접근
1) tie()
tie(a,b) = pi;: pair인pi로 부터 값을 가져와 변수a,b에 대입한다.tie(a,b,c) = tl;: tuple인tl로 부터 값을 가져와 변수a,b,c에 대입한다.
2) first, second
d = pi.first;
e = pi.second;
pair의 첫 번째와 두 번째 요소에 접근하는 데 사용.
3) get<>()
d = get<0>(tl);
e = get<1>(tl);
f = get<2>(tl);
Code language: HTML, XML (xml)
각각 tuple의 첫 번째, 두 번째, 세 번째 요소에 접근하는 데 사용.