메뉴 닫기

C++ pair Vector 정렬2

#include <iostream>		//cin, cout
#include <utility>		
#include <vector>		//vector
#include <algorithm>	//sort

using namespace std;

bool comp(const pair<int, string>&a, const pair<int, string>&b)
{
    if(a.first == b.first)		//first가 같다면 second로 정렬
        return a.second > b.second;
    return a.first > b.first;	//우선 pair의 first로 정렬
  	//return을 먼저 하면 comp가 끝나니 if문 먼저 함
}

int main()
{
    vector<pair<int, string>> p;	//숫자 문자의 쌍을 vector로 
    int n, no;
    string name;
    cin >> n;
    for(int i=0;i<n;i++)
    {
        cin >> no >> name;
        p.push_back(make_pair(no, name));
    }

  	cout << endl;
    for(int i=0; i<p.size(); i++)
        cout << p[i].first << " " <<p[i].second << endl;
	cout << endl;
  
    sort(p.begin(), p.end());

    for(int i=0; i<p.size(); i++)
        cout << p[i].first << " " <<p[i].second << endl;
	cout << endl;
  
    sort(p.begin(), p.end(), comp);

    for(int i=0; i<p.size(); i++)
        cout << p[i].first << " " <<p[i].second << endl;

    return 0;
}

답글 남기기

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다