정렬 : sort()

2023. 3. 28. 00:36프로그래밍/C++

sort() 함수는 STL에서 제공하는 알고리즘 중 하나로, 벡터와 같은 컨테이너를 정렬하는데 사용됩니다.

그러나 queue는 내부적으로는 연결리스트 형태로 구현되어 있으므로 sort()를 사용할 수 없습니다.

 

sort() 함수 : C++ algorithm 헤더에 포함

sort(배열의 시작점 주소, 마지막 주소 + 1)

 

#include <iostream>
#include <algorithm>
using namespace std;

void main(){
	int a[] = {9,3,5,4,1,10,8,6,7,2};
    sort(a, a + size(a));
    
    for(int obj : a){
    	cout<< obj << ' ' ;
    }
}

 

sort() 함수를 이용한 내림차순 정렬

#include <iostream>
#include <algorithm>
using namespace std;

bool compare(int a, int b){
	return a>b;
}

void main(){
	int a[] = {9,3,5,4,1,10,8,6,7,2};
    
    sort(a, a+size(a), compare);
    for(int i=0; i<size(a); i++){
    	cout << a[i] << ' ';
    }
}

 

특정 변수를 기준으로 정렬

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

class Student {
public:
	string name;
	int score;

	Student(string name, int score) {
		this->name = name;
		this->score = score;
	}

	bool operator <(Student &student) {
		return this->score < student.score;
	}
};

void main() {
	Student student[] = {
		Student("김",95),
		Student("박",80),
		Student("나",72),
		Student("이",99),
		Student("리",93),
	};

	sort(student, student + size(student));

	for (Student obj : student) {
		cout << obj.name << endl;
	}
}

 

'프로그래밍 > C++' 카테고리의 다른 글

연결리스트  (0) 2023.04.01
동적 할당  (0) 2023.04.01
포인터  (0) 2023.03.30
함수 오버로딩  (0) 2023.03.30
[C++] 변수 다루기  (0) 2023.03.27