반응형
Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
Tags
- singly Linked List
- deletion
- Biconnected_Component
- 총정리
- 문법
- data_structure
- sstream
- c++
- Articulation_Point
- qsort
- template
- list
- connected_component
- Heap
- 구현
- function_template
- 자료구조
- 알고리즘
- Algorithm
- '0'
- Critical_Path_Analysis
- red-black tree
- Pair
- 백준
- 예제
- 13305
- sort
- 5397
- STL
- class_template
Archives
- Today
- Total
- Today
- Total
- 방명록
어제의 나보다 성장한 오늘의 나
[C++] Pair 와 Tuple 본문
반응형
문제를 풀다보면 연관이 있는 데이터들을 묶어서 사용하고 싶을 때가 있다.
이 때 사용하는 기능이 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;
}
}
반응형
'c++ > 문법' 카테고리의 다른 글
[C++] Unique 함수 정리 및 예제 (0) | 2022.02.13 |
---|---|
[c / c++] new / malloc / calloc /realloc 총 정리 & 예제 (0) | 2022.02.12 |
[c++] [자료형] int / double / char / float 크기 (0) | 2022.02.12 |
[C++] Sort 와 Compare 함수 (Greater , less) (0) | 2022.02.10 |
[c++] Template(템플릿) 총 정리 & 예제 (0) | 2022.02.10 |
Comments