My Blog List

Sort

A trifle in C++ sort function.


If we want use sort function to sort a vector with self-defined data type, one method is passing a compare function as a parameter to sort.

The very clear details about how to define the comparison function  can be found here.

But check the following code to figure out if there is any problem?
#include<iostream>
#include<algorithm>
#include<vector>
#include<cstdlib>
using namespace std;
struct node{
    int a,b;
    node(int aa,int bb):a(aa),b(bb){}
};
bool cmp(node x,node y){
    return x.a<=y.a;
}
int main(){
    vector<node>v;
    v.push_back(node(1,2));
    v.push_back(node(1,2));
    v.push_back(node(1,2));
    v.push_back(node(1,2));
    v.push_back(node(1,2));
    v.push_back(node(1,3));
    v.push_back(node(1,4));
    v.push_back(node(1,2));
    v.push_back(node(1,2));
    v.push_back(node(1,3));
    v.push_back(node(1,4));
    v.push_back(node(1,2));
    v.push_back(node(1,2));
    v.push_back(node(1,3));
    v.push_back(node(1,4));
    v.push_back(node(1,3));
    v.push_back(node(1,4));
    v.push_back(node(1,3));
    v.push_back(node(1,4));
    v.push_back(node(1,5));
    v.push_back(node(2,3));
    v.push_back(node(2,3));
    v.push_back(node(3,4));
    sort(v.begin(),v.end(),cmp);
    for(int i=0;i<v.size();i++)
        cout<<v[i].a<<" "<<v[i].b<<endl;
    return 0;
}
It seems good right? However it will lead to segmentation fault.
It is because the comparison function requires the strict order of two items. Thus equal or less equal is not allowed to appear. The reason why is will crash can be talked later.

 Comparison between Qsort and Priority_queue

For sort, cmp is a function pointer or comparison object.
However for priority_queue, the comparison is a class template.
Consider the following code.



No comments:

Post a Comment

Enter you comment