pair 란?
한번에 두개의 자료형을 갖는 클래스.
사용자가 직접 지정.
그냥 클래스를 만들때 사용하기도 하지만 스택, 큐 등에 유용하게 사용
pair사용법
1.헤더파일 #include <uitiliy>
2.생성하기위해 pair<자료형1,자료형2> 클래스명(자료형1변수,자료형2변수)
3.첫번째 자료형을 보기 위해서는 클래스명.first, 두번째 자료형을 보기 위해서는 클래스명.second이다.
4.변수를 보기 위해서는 두가지 방법이 있다.
첫번째는 클래스명.first=새로운 변수, 클래스명.second=새로운 변수
두번째는 클래스명 = make_pair(첫번째 변수, 두번째 변수)이다.
#include <iostream>
//pair를 사용하기 위해서는 <utility>헤더파일 필요
#include <utility>
using namespace std;
int main()
{
//1.생성과 동시에 초기화
pair<int, char> x(15, 'a');
cout << x.first<<endl;
cout << x.second<<endl;
//2\. x.first, x.second에 직접 담아주기
x.first = 16;
x.second = 'b';
cout << x.first << endl;
cout << x.second << endl;
//3.make_pair(int,char)로 초기화
x = make_pair(17, 'c');
cout << x.first << endl;
cout << x.second << endl;
return 0;
}
pair로 세개짜리 변수를 갖는 클래스 만들기
다음과 같이 하면 된다.
pair<pair<int, int>, int> ppp;
ppp.first.first = 1;
ppp.first.second = 2;
ppp.second = 3;
cout << ppp.first.first << endl << ppp.first.second <<endl<< ppp.second;
pair를 stack 과 queue에 응용
queue<pair<int, int>> q;
q.push(make_pair(33, 32));
cout << q.front().first << endl << q.front().second<<endl;
stack<pair<int, char>> s;
s.push(make_pair(31, 'a'));
cout << s.top().first << endl << s.top().second;
'언어 > CPP(cpp)' 카테고리의 다른 글
c++ 벡터,큐,스택 정리 (비교) (0) | 2019.02.09 |
---|---|
c++무한대표현하기.무한값 표현하기 (0) | 2018.11.04 |
템플릿 (0) | 2018.02.06 |
오버라이딩 (0) | 2018.02.06 |
상속 (0) | 2018.02.06 |