본문 바로가기

알고리즘 문제풀이/알고리즘

[c++] sort 함수 / 내림차순 / 커스텀 정렬

http://www.cplusplus.com/reference/algorithm/sort/

 

sort - C++ Reference

custom (2)template void sort (RandomAccessIterator first, RandomAccessIterator last, Compare comp);

www.cplusplus.com

기본 사용법

#include <string>
#include <vector>
#include <algorithm>

using namespace std;

int main(){
  int myints[] = {32,71,12,45,26,80,53,33};
  vector<int> myvector (myints, myints+8);

  // using default comparison (operator <):
  sort (myvector.begin(), myvector.begin()+4); //(12 32 45 71)26 80 53 33
  
  // compare all
  sort (myvector.begin(), myvector.end());
}

 

 

내림차순

#include <string>
#include <vector>
#include <functional> // greater
#include <algorithm>

using namespace std;

int main(){
  int myints[] = {32,71,12,45,26,80,53,33};
  vector<int> myvector (myints, myints+8);

  sort (myvector.begin(), myvector.end(), greater<int>());
}

 

나만의 비교함수 만들기

#include <string>
#include <vector>
#include <functional>
#include <algorithm>

using namespace std;

bool myfunction (int i,int j) { return (i<j); }

int main(){
  int myints[] = {32,71,12,45,26,80,53,33};
  vector<int> myvector (myints, myints+8);

  // using function as comp, ascending order
  sort(myvector.begin()+4, myvector.end(), myfunction); // 12 32 45 71(26 33 53 80)
}​