본문으로 바로가기

C++11) std::tuple

category C++/Modern 2019. 2. 10. 18:00

<개요>


std::tuple은 가변인자 타입으로써, std::pair의 일반형입니다.

예전엔 2개 이상의 값을 반환 하려면 구조체를 이용해 입력해줬어야 하지만 이젠 std::tuple로 가능합니다.


<std::tuple>


tuple을 사용하려면 기본적으로 <tuple> 헤더를 포함하셔야 합니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
#include <tuple>
#include <string>
using namespace std;
int main() {
    typedef std::tuple<doublecharstd::string> sc;
    std::tuple<doublecharstd::string> sc1 = std::make_tuple<doublecharstd::string>(3.8'A'"김덕배");
    auto sc2 = std::make_tuple<doublecharstd::string>(3.4'B'"김아무개");    // 가장 일반적인 방법
    sc sc3 = std::make_tuple<doublecharstd::string>(0.0'F'"박아무개");    // typedef 로도 제작 가능
    std::tuple<doublecharstd::string> sc4(1.0'D'"엄아무개");                // 이런식으로도 가능
    cout << std::get<0>(sc1) << endl;    // 3.8
    cout << std::get<1>(sc1) << endl;    // A
    cout << std::get<2>(sc1) << endl;    // 김덕배
    std::get<0>(sc1) = 4.5;    // sc1의 0번째 요소인 3.8을 4.5로 변경합니다.
}
cs

반환형으로도 사용할 수 있습니다.

1
2
3
4
5
6
7
8
9
10
11
using namespace std;
decltype(auto) getScore(double _s, char _g, std::string _name) {
    auto tmp = make_tuple(_s, _g, _name);
    return tmp;
}
int main() {
    auto abc = getScore(4.5'A'"엄준식");
    cout << std::get<0>(abc) << endl;    // 4.5
    cout << std::get<1>(abc) << endl;    // A
    cout << std::get<2>(abc) << endl;    // 엄준식
}
cs


또한 크기도 알아낼 수 있습니다.

1
2
3
4
5
6
7
8
9
template<typename... Args>
int getCount(std::tuple<Args...> A){
    return std::tuple_size<decltype(A)>::value;
}
int main() {
    auto abc = getScore(4.5'A'"엄준식");
    int count = std::tuple_size<decltype(abc)>::value;    // count == 3
    int cc = getCount(abc);    //cc == 3
}
cs


tie 함수를 이용해 값을 한번에 읽어오거나, 빼올 수 있습니다.

1
2
3
4
    double a;
    char b;
    std::string c;
    std::tie(a, b, c) = abc;    // a 는 4.5 b는 A c는 엄준식이 들어갑니다.count == 3
cs



tuple_cat 함수를 이용해 튜플을 합칠 수 있습니다.

1
2
3
4
    auto abc = getScore(4.5'A'"엄준식");
    auto def = getScore(0.0'F'"김아무개");
 
    auto g = std::tuple_cat(abc, def); // g는 4.5 A 엄준식 0.0 F 김아무개 가 들어갑니다.
cs



참고 ) 튜플 반복에 대한 정보

https://code.i-harness.com/ko-kr/q/1248b4