对vector模板进行排序的方法——sort, stable_sort, qsort

I am trying to sort the "sth" integer value within the vector of class Entry using qsort. The code for the same is as follows. But after applying qsort, also the values remain the same. When I tried to print the values in cmpfunc2(), I found that 0 0 is getting printed.

#include
#include
#include
using namespace std;
class Entry{public:
int id;
int sth;

Entry(int,int);
};
 Entry::Entry(int a,int b){
  id=a;
  sth=b;
}
int cmpfunc2 (const void * a, const void * b)
{
   cout<<(*(Entry *)a).sth<<"  "<<(*(Entry *)b).sth < entries;

entries.push_back(Entry(2,3));
entries.push_back(Entry(21,14));
entries.push_back(Entry(54,12));

qsort(&entries, entries.size(),sizeof(Entry),cmpfunc2);
  for(int i=0;i

Solution:

Change this statement

qsort(&entries, entries.size(),sizeof(Entry),cmpfunc2);

to

qsort( entries.data(),  entries.size(), sizeof( Entry ), cmpfunc2 );
qsort( &entries[0],  entries.size(), sizeof( Entry ), cmpfunc2 );

However it would be better to use standard algorithm std::sort declared in header . For example

#include 

//...

bool cmpfunc2 ( const Entry &a, const Entry &b )
{
   return ( a.sth < b.sth );
}

// ...

std::sort( entries.begin(), entries.end(), cmpfunc2 );

Or you could use std::stable_sort

std::stable_sort( entries.begin(), entries.end(), cmpfunc2 );

Also consider the posiibility to compare objects of type Entry as objects of type std::pair. In this case objects with equal sth will be sorted according to id. For example

#include 
#include 

//... 

bool cmpfunc2 ( const Entry &a, const Entry &b )
{
   return ( std::make_pair( a.sth, a.id )  < std::make_pair( b.sth, b.id ) );
}

 

你可能感兴趣的:(对vector模板进行排序的方法——sort, stable_sort, qsort)