1. sort란
인자를 간단하게 정렬해주는 함수
2. sort를 사용하기 위한 헤더파일
#include <algorithm>
3. sort의 여러 종류
sort(배열의 포인터, 배열의 포인터 + 배열의 크기)
sort(arr, arr+n)
sort는 기본적으로 오름차순(내림차순은 greater이용sort(arr, arr + N,greater<int>());
)
으로 정렬된다. 첫번째는 배열을 사용해서 정렬한 것이고 두번째는 벡터를 사용해 정렬한 것이다. 배열을 이용하여 정렬하고자 할때는 배열의 시작점 주소와 마지막 주소 + 1를 적어야 한다.
#include <iostream>
#include <algorithm>
#include <stdio.h>
using namespace std;
int main(void) {
int a[10] = {9, 3, 5, 4, 1, 10, 8, 6, 7, 2};
sort(a, a + 10);
for(int i = 0; i < 10; i++) {
printf("%d ",a[i])
}
}
sort(v.begin(), v.end());
#include <algorithm>
#include <stdio.h>
#include <vector>
using namespace std;
int main(void) {
vector <int> v;
v.push_back(9);
v.push_back(3);
v.push_back(5);
v.push_back(4);
v.push_back(1);
v.push_back(10);
v.push_back(8);
v.push_back(6);
v.push_back(7);
v.push_back(2);
sort(v.begin(), v.end());
for(int i = 0; i < 10; i++) {
printf("%d ",v[i])
}
}
sort(v.begin(), v.end(), compare);
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
using namespace std;
class Product {
public:
string pname;
int pay;
Product(string pname, int pay) : pname(pname), pay(pay) {}
};
bool compare(Product a, Product b) {
if (a.pay == b.pay) {
return a.pname < b.pname; // 페이가 같으면 이름 가나다라 순
}
else {
return a.pname > b.pname; // 페이가 다르면 작은 순부터
}
}
int main(void)
{
vector<Product> v;
v.push_back(Product("멘토스", 700));
v.push_back(Product("멘토스", 1000));
v.push_back(Product("비틀즈", 700));
v.push_back(Product("비틀즈", 1200));
v.push_back(Product("새콤달콤", 500));
sort(v.begin(), v.end(), compare);
for (int i = 0; i < 5; i++) {
cout << v[i].pname << " : " << v[i].pay << endl;
}
return 0;
}
compare 함수를 이용하여 사용자가 원하는 정렬을 할 수 있게 만든다.