어제의 나보다 성장한 오늘의 나

[C++] Pair 와 Tuple 본문

c++/문법

[C++] Pair 와 Tuple

today_me 2022. 2. 10. 23:20
반응형

문제를 풀다보면 연관이 있는 데이터들을 묶어서 사용하고 싶을 때가 있다.
이 때 사용하는 기능이 Pair 와 Tuple이다.


Pair는 2쌍 , Tuple은 3쌍 으로 묶을 수 있다.

헤더 파일

Pair -> #include <utility> (생략 가능)

Tuple -> #include <tuple>

 

----------------------------------------------------------------------------------------------------------------------------------

Pair Coding

 

vector<pair<int, string>> v_pair; // vector 에서의 pair 사용.

    v_pair.push_back(make_pair(1,"first")); // pair는 <make_pair> function 을 통해 만들 수 있다.
    // v_pair.push_back({1,"first"}); 도 가능.
    v_pair.push_back(make_pair(2,"second"));
    v_pair.push_back(make_pair(3,"third"));
    
    for(auto x : v_pair){
        // first , second로 첫 번째 type , 두 번째 type에 접근 가능
        cout << "first elem : " << x.first << " || second elem : " << x.second << endl; 
        }

 

 

 

Tuple Coding

 

vector<tuple<int,char,string>> v_tuple; // vector에서의 pair 사용.

    v_tuple.push_back(make_tuple(1,'a',"apple")); //tuple은 <make_tuple> function을 통해 만들 수 있다.
    // v_tuple.push_back({1,'a',"apple"}) 도 가능.
    v_tuple.push_back(make_tuple(2,'b',"bus"));
    v_tuple.push_back(make_tuple(3,'c',"column"));

    for(auto x : v_tuple){
        // get 함수와 <순서> 를 통해 3개의 type에 접근 가능.
        cout << "first elem : " << get<0>(x) << " || second elem : " << get<1>(x) << " || third elem : " << get<2>(x) << endl; 
    }

 

 

전체 Coding

 

#include <iostream>
#include <utility>
#include <tuple>
#include <vector>

using namespace std;



int main(int args ,char** argv){
    vector<pair<int, string>> v_pair; 

    v_pair.push_back(make_pair(1,"first")); 
    v_pair.push_back(make_pair(2,"second"));
    v_pair.push_back(make_pair(3,"third"));
    
    for(auto x : v_pair){
        cout << "first elem : " << x.first << " || second elem : " << x.second << endl; 
        }

    vector<tuple<int,char,string>> v_tuple;

    v_tuple.push_back(make_tuple(1,'a',"apple"));
    v_tuple.push_back(make_tuple(2,'b',"bus"));
    v_tuple.push_back(make_tuple(3,'c',"column"));

    for(auto x : v_tuple){
        cout << "first elem : " << get<0>(x) << " || second elem : "\
        << get<1>(x) << " || third elem : " << get<2>(x) << endl; 
    }
}

 

반응형
Comments