프로그래밍/C, C++

연산자 오버라이딩, sort, 생성자

즉흥 2015. 6. 7. 13:46
728x90
반응형
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include<cstdio>
#include<algorithm>
struct block{
    int n, a, h, w;
    block(){}
    block(int n, int a, int h, int w)
        :n(n), a(a), h(h), w(w)
    {}
    bool operator<(const block &cmp) const {
        return a < cmp.a;
    }
};
int main(){
    freopen("input.txt","r",stdin);
    block b[104];
    int n;
    scanf("%d",&n);
    for(int i=0;i<n;i++){
        int a, h, w;
        scanf("%d%d%d",&a,&h,&w);
        b[i] = block(i+1, a, h, w);
    }
    std::sort(b, b+n);
    return 0;
}
cs





구조체에 생성자로 저렇게 넣고,


sort 함수는 내부에서 < 연산자를 사용하니까


연산자 오버라이딩(operator)으로 저렇게 구조체를 비교할 수 있게 하면 끝.



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream> 
#include <queue> 
using namespace std
 
struct compare { 
    bool operator()(const int& l, const int& r) { 
        return l > r; 
    } 
}; 
 
int main() { 
    priority_queue<int,vector<int>, compare > pq; 
 
    pq.push(3); 
    pq.push(5); 
    pq.push(1); 
    pq.push(8); 
    while ( !pq.empty() ) { 
        cout << pq.top() << endl
        pq.pop(); 
    } 
    cin.get(); 
    return 0;
}
cs

Priority_queue는 () 연산자를 사용한다.


1
2
3
4
5
6
7
8
9
10
11
#include<cstdio>
#include<algorithm>
#include<functional>
using namespace std;
int main() {
    int arr[] = { 5,1,4,2,3 };
    sort(arr, arr + 5, greater<int>());
    for(int i=0;i<5;i++)
        printf("%d ", arr[i]);
    return 0;
}
cs

내림차순 greater()는 덤

728x90
반응형