How do I sort a vector of struct using different methods ?

Hi experts,

typedef struct{
  int head ;
  int tail ;
  // ... blah
} Animal ;

I want to sort vector<Animal>. In some cases I want to sort by head; but in other cases, I want to sort by tail ....

so how do I do this ? should I write a predicator ? if so, how to do it ?

many thanks !
LVL 1
meow00Asked:
Who is Participating?
 
Julian HansenCommented:
Sorry - just read your full post properly.

Because you want to sort on different element you will need to write a predicate function for each method you want to use. Refer to the sample code below

Eg.

#include "windows.h"
#include <tchar.h>
#include "stdio.h"
#include <vector>
#include <algorithm>

using namespace std ;

typedef struct
{
      int head ;
      int tail ;
} ANIMAL ;

bool SortByHeadDesc ( ANIMAL elem1, ANIMAL elem2 )
{
      return elem1.head > elem2.head ;
}

bool SortByTailDesc ( ANIMAL elem1, ANIMAL elem2 )
{
      return elem1.tail > elem2.tail ;
}

bool SortByHeadAsc ( ANIMAL elem1, ANIMAL elem2 )
{
      return elem1.head < elem2.head ;
}

bool SortByTailAsc ( ANIMAL elem1, ANIMAL elem2 )
{
      return elem1.tail < elem2.tail ;
}

int _tmain(int argc, _TCHAR* argv[])
{
      vector<ANIMAL> vec ;
      ANIMAL elem1 = {1,30} ;
      ANIMAL elem2 = {2,20} ;
      ANIMAL elem3 = {7,90} ;
      ANIMAL elem4 = {9,15} ;
      ANIMAL elem5 = {3,10} ;

      vec.push_back ( elem1  ) ;
      vec.push_back ( elem2  ) ;
      vec.push_back ( elem3  ) ;
      vec.push_back ( elem4  ) ;
      vec.push_back ( elem5  ) ;


      vector<ANIMAL>::iterator it ;

      printf ( "Sort by head (first element) Descending\n" ) ;
      sort ( vec.begin(), vec.end(), SortByHeadDesc ) ;
      for ( it = vec.begin(); it != vec.end(); it++ )
      {
            printf ( "%d, %d\n", it->head, it->tail ) ;
      }


      printf ( "\nSort by tail (second element) Descending\n" ) ;
      sort ( vec.begin(), vec.end(), SortByTailDesc ) ;
      for ( it = vec.begin(); it != vec.end(); it++ )
      {
            printf ( "%d, %d\n", it->head, it->tail ) ;
      }

      printf ( "Sort by head (first element) Ascending\n" ) ;
      sort ( vec.begin(), vec.end(), SortByHeadAsc ) ;
      for ( it = vec.begin(); it != vec.end(); it++ )
      {
            printf ( "%d, %d\n", it->head, it->tail ) ;
      }

      printf ( "\nSort by tail (second element) Ascending\n" ) ;
      sort ( vec.begin(), vec.end(), SortByTailAsc ) ;
      for ( it = vec.begin(); it != vec.end(); it++ )
      {
            printf ( "%d, %d\n", it->head, it->tail ) ;
      }

      return 0;
}

0
 
Julian HansenCommented:
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.