STL pair
pair 클래스는 STL에서 두 객체를 하나의 객체로 취급 할 수 있게 묶어주는 클래스다. pair의 사전적의미처럼 쌍 을 표현할 때 사용하며 <utility>
헤더에 존재한다.
구조
template <class T1, class T2> struct pair;
template <typename T1, typename T2> struct pair;
멤버함수
생성자 / 멤버함수
설명
pair<[type1],[type2]> p
사용할 데이터 타입을 넣고 그 타입의 pair클래스인 p를 생성
p.first
p의 첫번째 인자를 리턴
p.second
p의 두번째 인자를 리턴
make_pair(var1,var2)
var1과 var2가 들어간 pair를 생성
연산
비교 연산자(
==
,!
,<
,>
,<=
,>=
)sort 알고리즘에 의해 정렬 가능
첫번째 인자를 기준으로 비교
첫번째 인자가 같다면 두번째 인자로 비교
예제
<int, String>
#include<iostream>
#include<utility>
#include<string>
using namespace std;
int main(void){
pair<int, string> p1 = make_pair(1,"test1");
pair<int, string> p2 = make_pair(3,"test3");
cout << "p1.first : " << p1.first << endl;
// p1.first : 1
cout << "p1.second : " << p1.second << endl;
// p1.second : test1
return 0;
}
vector 컨테이너 타입으로 사용
#include<iostream>
#include<utility>
#include<string>
#include<vector>
using namespace std;
int main(void){
vector<pair<int, string> > v;
v.push_back(pair<int, string>(3, "Dok2"));
v.push_back(pair<int, string>(6, "DMask"));
v.push_back(pair<int, string>(1, "Tiger JK"));
v.push_back(pair<int, string>(4, "Block"));
v.push_back(pair<int, string>(2, "banana"));
v.push_back(pair<int, string>(2, "apple"));
vector<pair<int, string> >::iterator i;
for(i = v.begin(); i != v.end(); i++){
cout << "[" << i->first << "," << i->second << "]" << endl;
}
return 0;
}
sort 예제
#include<algorithm>
using namespace std;
int main(void){
vector<pair<int, string> > v;
v.push_back(pair<int, string>(3, "Dok2"));
v.push_back(pair<int, string>(6, "DMask"));
v.push_back(pair<int, string>(1, "Tiger JK"));
v.push_back(pair<int, string>(4, "Block"));
v.push_back(pair<int, string>(2, "banana"));
v.push_back(pair<int, string>(2, "apple"));
cout << "=== After sort === " << endl;
sort(v.begin(), v.end());
for(iter = v.begin(); iter != v.end(); iter++){
cout << "[" << iter->first << "," << iter->second << "]" << endl;
}
return 0;
}
참조페이지
http://blockdmask.tistory.com/64
Last updated
Was this helpful?