pair는 서로 다른 데이터 유형일 수 있는 두 값을 함께 저장할 때 사용된다.
note: #include <utility> 헤더를 사용한다.
원소 담는 방법 1
#include <iostream>
#include <utility>
using namespace std;
int main()
{
pair<int, char> p;
p.first = 65;
p.second = 'A';
cout << p.first << " ";
cout << p.second << endl;
return 0;
}
Output
65 A
원소 담는 방법 2
#include <iostream>
#include <utility>
using namespace std;
int main()
{
pair<int, char> p;
p = make_pair(66, 'B'); // make_pair 함수 사용
cout << p.first << " ";
cout << p.second << endl;
return 0;
}
Output
66 B
원소 담는 방법 3
#include <iostream>
#include <utility>
using namespace std;
int main()
{
pair<int, char> p;
p = {67, 'C'};
cout << p.first << " ";
cout << p.second << endl;
return 0;
}
Output
67 C
이 외에도 여러가지 방법이 있다. 그렇다면 원소를 access하는 방법으로는 무엇이 있는지 알아보자!
원소 접근 방법 1
#include <iostream>
#include <utility>
using namespace std;
int main()
{
pair<string, int> p;
p = {"Hello World", 1};
cout << p.first << " "; // p.first (첫 번째 값)
cout << p.second << endl; // p.second (두 번째 값)
return 0;
}
Output
Hello World 1
원소 접근 방법 2
note: tie 사용을 위하여 #include <tuple> 헤더를 사용한다.
#include <iostream>
#include <tuple>
#include <utility>
using namespace std;
int main()
{
pair<string, int> p;
p = {"Hello World", 1};
string s; int a;
tie(s, a) = p; // tie 사용
cout << s << " ";
cout << a << endl;
return 0;
}
Output
Hello World 1
'C++' 카테고리의 다른 글
[C++] tuple 사용법 (0) | 2023.07.11 |
---|