# How can I use sort with a pointer vector?

4

I'm trying to use sort with a vector type `vector<node*>` where `node` is a variable that I created myself. However I am not succeeding, it does not let me put that function inside the sort method. This is my code:

``````int compOrganizar(node* nodo1, node* nodo2){

return (nodo1->getF() < nodo2->getF());
}

void expandir_nodo(node nodo){

if (isGoal(nodo)){

haveSol = true;
}

else{
generateIzquierda(nodo);
generateDerecha(nodo);

sort(abiertos.begin(),abiertos.end(),compOrganizar);
}
``````

Would anyone know how to tell me what I have wrong? Thank you in advance to everyone.

asked by Alfonso Rodríguez 15.12.2017 в 12:53
source

5

You can use the `std::sort` `<algorithm>` :

``````std::vector<node *> nodos;

// rellenar vector...

// ordenar el vector...
std::sort(nodos.begin(), nodos.end());
``````

But since the type stored in the `std::vector` is a pointer it will sort you by the value of the pointer, which does not make any sense.

Luckily, `std::sort` accepts an additional parameter that consists of a function to sort your type, assuming you want to sort the nodes by `node::getF` you could do:

``````std::vector<node *> nodos;

// rellenar vector...

// ordenar el vector...
std::sort(nodos.begin(), nodos.end(), [](const node *&a, const node *&b)
{
return a->getF() < b->getF();
});
``````

The third parameter that I am passing to `std::sort` is a lambda expression .

source
5

It is not working because the function that expects `sort` must return a Boolean:

``````   bool compOrganizar(node* nodo1, node* nodo2){
// ^^^^

return (nodo1->getF() < nodo2->getF());
}
``````

We must not lose sight of the fact that C ++ is based on a strong typing ... it is more fussy than the compiler of C