Tuple 간단한 정리

jahlee·2023년 1월 4일
0

개인 공부

목록 보기
3/23

tuple은 객체 지향 언어에서 사용되고 c++11에서 채택되어 제공되어진다.비슷한 개념으로 pair가 있지만 pair의 경우 데이터의 형이 두개 이상이게 되면 사용이 불가능 하기 때문에 이러한 경우 tuple을 사용하면 된다.

std::tuple<int,char,int> t;

위와같은 형식으로 선언할 수 있으며 데이터를 추가할 때는

make_tuple(1,c,3)

이와 같은 형식으로 사용 가능하다.
예시로 queue에서 tuple을 사용하는 경우에는 다음과 같다.

queue<tuple<int,int,int>> q;
q.push(make_tuple(1,2,3));
q.push({1,2,3});

데이터에 접근하는 방법은

get<index>(선언한 tuple);

ex)
queue<tuple<int,int,int>> q;
q.push(make_tuple(1,2,3));
cout << get<0>(q.front());

과 같이 접근하면 된다.

간단한 예시

#include <iostream>
#include <queue>
#include <tuple>
using namespace std;

int main()
{
	queue<tuple<int,int,int> > q;
	q.push(make_tuple(1,2,3));
	cout << get<0>(q.front()) << get<1>(q.front()) << get<2>(q.front()) << "\n"; // 123
	q.pop();
	q.push({4,5,6});
	cout << get<0>(q.front()) << get<1>(q.front()) << get<2>(q.front()) << "\n"; // 456
}

0개의 댓글