프로그래머스 - 문자열 내 마음대로 정렬하기

108번뇌·2020년 10월 2일
0


[방법1]

#include <string>
#include <vector>
#include <algorithm>
using namespace std;
int number;
bool cmp(string a, string b)
{
    if(a[number] != b[number])
    {
        return a[number]<b[number];
    }
    else
    {
        return a<b;
    }
}

vector<string> solution(vector<string> strings, int n) {
    vector<string> answer;
 number = n;
 sort(strings.begin(), strings.end(), cmp);
  for(int i=0; i<strings.size(); i++)
  {
      answer.push_back(strings[i]);
  }
    return answer;
}

자주쓰는 방법.
sort에서 cmp함수 매개변수 3번째로 넣고
bool cmp(type cmp1, type cmp2)
{
return cmp1>cmp2; : 내림차순
return cmp1<cmp2; : 오름차순
}

[방법2]

#include <string>
#include <vector>
#include <algorithm>
using namespace std;



vector<string> solution(vector<string> strings, int n) {
vector<string> answer;
 vector<pair<int,string>> V;
    for(int i=0; i<strings.size(); i++)
    {
        V.push_back(make_pair(strings[i][n], strings[i]));
    }
    sort(V.begin(),V.end());
    for(int i=0; i<strings.size(); i++)
    {
        answer.push_back(V[i].second);
    }
    
    return answer;
}

[Vector - pair의 활용]
먼저 vector<pair<Type1, Type2>> V;
V.push_back(make_pare(Type1 T, Type2 2));
이후 sort(v.begin(),v.end()); 했을때,
V.first 기준으로 sort 오름차순으로 간다.
만약에 같은게 있을경우 second로 또 정한다.

profile
내일 아침 눈을 떳을 때, '기대되는 오늘 하루를 만들기 위해' 나는 오늘도 생각하고 고민한다.

0개의 댓글