comparision function in stl::sort()
class node{
public:
unsigned long long int value;
int index;
};
bool comp2(node& a,node& b){
if(a.value < b.value) { return true; }
return false;
}
vector <node*>llis开发者_StackOverflowt,rlist;
sort(llist.begin(),llist.end(),comp2);
Above code was giving me some weired error that is too in some other lines(places latter in code), but when i changed comp2 function to following all error disappeared .
bool comp2(node* a,node* b){
assert(a && b && "comp2 - null argument");
if(a->value < b->value){ return true; }
return false;
}
Any rationale on this ?
ERROR:/usr/include/c++/4.4/bits/stl_algo.h|124|error: invalid initialization of reference of type ‘node&’ from expression of type ‘node* const’|
If this(bellow) works then above should also work
using namespace std;
void rep(int& a,int& b){
int c;
c=a;
a=b;
b=c;
}
int main(void){
int a=3,b=4;
rep(a,b);
cout<<a<<" "<<b;
return 0;
}
You have defined a std::vector
of node *
. Therefore, all the elements are node *
, and all operations that the vector performs will be on node *
. You can't give sort
a comparison function of a different type.
The rational is that your vector contains values of type node*
, so the comparison functions needs to compare values of type node*
.
What you probably meant to say in the first place was vector<node>
. If you wanted pointers to nodes, then the second comparison function is reasonable.
精彩评论