How to sort an array using two attributes?

Asked

Viewed 51 times

0

Come on... I have a class Student, which contains the attributes name, idCurst and situation. I also have a vector that stores several objects of the Student type. I also have a method ordain() that returns to me a vector ordered by course. Follows the method:

    vector<Aluno> ordenaPorCurso(Vector<Aluno> lista){
         for(int i = 0 ; i < lista.size() ; i++){
            for(int j = i ; j < lista.size() ; j++){

                if(lista[i].getCurso() >= lista[j].getCurso()){

                    Aluno temp = lista[j];
                    lista[j] = lista[i];
                    lista[i] = temp;

                }
            }
        }return lista;

My question is this: I need to create a method that sorts by course And Name and I’m stuck. Someone can help me?

Grateful.

  • Makes a < operator Overload saying how you want instances of the Student class to be ordered. Then you can use the Sort function to sort your vector.

1 answer

0


To sort by two fields you must compare in this order:

  1. if the first field of an element is greater that of the other element;
  2. if the first field of an element is equal to that of the other element and the second field is greater or equal to that of the other element;

Therefore, the comparison between the two elements would be as follows::

if ((lista[i].getCurso()  > lista[j].getCurso()) ||
    (lista[i].getCurso() == lista[j].getCurso()  && lista[i].getNome() >= lista[j].getNome())) {
  • Got it! Thanks! What if it was the comparison between three elements? What would it look like?

  • For three elements just compare the third field when the first and the second are equal. The code gets a little complicated to do all this in one if, then I suggest separating into more than one operation or implementing comparison operators. If you want the code ask a proper question I’ll put the code there.

  • https://answall.com/questions/440878/howto sort-um-vector-using-tr%C3%aas-attributes

Browser other questions tagged

You are not signed in. Login or sign up in order to post.