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 ์•Œ๊ณ ๋ฆฌ์ฆ˜์— ์˜ํ•ด ์ •๋ ฌ ๊ฐ€๋Šฅ

    • ์ฒซ๋ฒˆ์งธ ์ธ์ž๋ฅผ ๊ธฐ์ค€์œผ๋กœ ๋น„๊ต

    • ์ฒซ๋ฒˆ์งธ ์ธ์ž๊ฐ€ ๊ฐ™๋‹ค๋ฉด ๋‘๋ฒˆ์งธ ์ธ์ž๋กœ ๋น„๊ต

์˜ˆ์ œ

#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;    
}

์ฐธ์กฐํŽ˜์ด์ง€

Last updated