How can I organize at once by two parameters with sort in C++?

Question:

I have this code:

bool Organizar(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(),Organizar);
    }

    nodos_expandidos++;
}

I have everything set up to organize the "open" vector by "f" but there is one more parameter inside the "node" object that I would like to organize the vector by. I would like to order the list by the objects that have less f (node.getF()) and others, among them, that have less h (node.getH).

Does anyone know how? Many thanks!

Answer:

Then make a small modification to your Organizar( ) function:

bool Organizar( node nodo1, node nodo2 ) {
  if( nodo1.getF( ) == nodo2.getF( ) )
    return nodo1.getH( ) < nodo2.getH( );

  return nodo1.getF( ) < nodo2.getF( );
}

But… if we take a closer look, your function should look like this:

bool Organizar( const node &nodo1, const node &nodo2 ) {
  if( nodo1.getF( ) == nodo2.getF( ) )
    return nodo1.getH( ) < nodo2.getH( );

  return nodo1.getF( ) < nodo2.getF( );
}

With which we will avoid unnecessary copies of objects, gaining in speed and security (by using const ).

Scroll to Top