C++ std::tie

오현진·2024년 6월 14일

C++ 

목록 보기
10/26
  • std::tie는 C++11에 도입된 유틸리티 함수로, 여러 개의 변수를 하나의 튜플(tuple)로 묶어주는 기능을 합니다.
  • 이를 통해 변수들을 한꺼번에 초기화하거나 할당할 수 있습니다. 특히 std::tie는 주로 std::pair나 std::tuple에서 값을 추출할 때 사용됩니다.

예시

#include <iostream>
#include <tuple>
#include <queue>

int main() {
    std::queue<std::pair<int, int>> virus_queue;
    virus_queue.push({1, 2});
    virus_queue.push({3, 4});

    while (!virus_queue.empty()) {
        int r, c;
        std::tie(r, c) = virus_queue.front(); // 큐의 front 요소를 r과 c로 분리
        virus_queue.pop();
        std::cout << "r: " << r << ", c: " << c << std::endl;
    }

    return 0;
}
r: 1, c: 2
r: 3, c: 4

기능 및 사용법

  1. 튜플에서 값 추출

    • std::tie는 튜플이나 페어에서 값을 추출할 때 사용됩니다.
    • 다음은 튜플에서 값을 추출하는 예시입니다.
    
    #include <tuple>
    #include <iostream>
    
    int main() {
        std::tuple<int, double, std::string> t = std::make_tuple(1, 2.5, "Hello");
    
        int a;
        double b;
        std::string c;
    
        std::tie(a, b, c) = t;
    
        std::cout << "a: " << a << ", b: " << b << ", c: " << c << std::endl;
    
        return 0;
    }
  2. 리턴 값으로 사용

    • 함수에서 여러 값을 리턴할 때 std::tie를 사용할 수 있습니다.
    
    #include <tuple>
    #include <iostream>
    
    std::tuple<int, double, std::string> getValues() {
        return std::make_tuple(42, 3.14, "example");
    }
    
    int main() {
        int a;
        double b;
        std::string c;
    
        std::tie(a, b, c) = getValues();
    
        std::cout << "a: " << a << ", b: " << b << ", c: " << c << std::endl;
    
        return 0;
    }
  3. 무시할 값이 있을 때

    • 필요 없는 값을 무시하고 싶을 때 std::ignore를 사용할 수 있습니다.
    
    #include <tuple>
    #include <iostream>
    
    std::tuple<int, double, std::string> getValues() {
        return std::make_tuple(42, 3.14, "example");
    }
    
    int main() {
        int a;
        std::string c;
    
        std::tie(a, std::ignore, c) = getValues();
    
        std::cout << "a: " << a << ", c: " << c << std::endl;
    
        return 0;
    }

0개의 댓글