tags:

views:

82

answers:

2

I have a class named Graph, in this class I have a member named V, it is a vector. I have a struct named Edge, and a list of Edges. like below:

struct Edge{
 int u;
 int v;
 Edge(int u,int v){
   this->u=u;
   this->v=v;
 }
};
struct Vertex{
 int d;
 int f;
 .
 .
 .
}

class Graph{
  vector < Vertex > V;
  .
  .
  .
  int edgeCmp(Edge* x,Edge* y){
    return ( V[x->v].d < V[y->v].d )?1:0;
  }
  void someFunction(){
   list<Edge> backEdges;
   backEdges.sort(&Graph::edgeCmp);
  }
}

But it doesn't work!! may someone help me to do such a thing? I get this error:

Error 3 error C2064: term does not evaluate to a function taking 2 arguments c:\program files\microsoft visual studio 9.0\vc\include\xutility 346

It can't understand I'm calling the function which takes 2 arguments. I don't know why.

+1  A: 
return (V[x->v].dv].d)?1:0;

This line has unbalanced brackets and is horrible to read (the former is a consequence of the latter I suspect). Without seeing your Vertex class it's hard to say what it is supposed to do - after fixing the brackets, maybe you should reformat for readability.

scomar
I added Vertex struct, but it is not the case. I get the error like this:term does not evaluate to a function taking 2 arguments
Morteza M.
@Morte Try declaring `edgeCmp` as `static`. Also, you should change the return type to `bool` and drop the `?1:0` part.
FredOverflow
+5  A: 

You can't use a member function as the comparator. A member function needs the this pointer which cannot be passed from sort.

Instead, you have to create a function object to include the extra info, like:

class Graph{
  vector < Vertex > V;

  struct EdgeComparer {
     const vector<Vertex>& V;
     EdgeComparer(const vector<Vertex>& vertices) : V(vertices) {}
     bool operator() (const Edge& a, const Edge& b) const {
        return V[a.v].d < V[b.v].d;
     }
  };

  ...

  EdgeComparer ec (V);
  backEdges.sort(ec);

Note that, since you have a list of Edge, not Edge*, the input arguments of the comparator should not be Edge*. I have changed those to const Edge&.

KennyTM
thank you! it works. but may you explain it to me?I couldn't understand it well.
Morteza M.
@Morteza: `.sort` can accept any object `f` that can be called like `f(a,b)`. Functions are an obvious type of them, but so are classes (structs) with overloaded `operator()`. The latter is called a function object. The advantage over normal functions is these can store an arbitrary state, like what is done here — the vertex vector `V` is included as an extra state of the function object, which is needed to compare the two Edge's.
KennyTM