Sorting a vector of structs

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Philia
    New Member
    • Dec 2007
    • 5

    Sorting a vector of structs

    Hi there,

    I have struct like this one:

    Code:
    struct kurs
    {
    		unsigned short int var1;
    		string string_var;
    		int sort_var;
    };
    // and a vector like this one
    Code:
    vector < struct kurs> kurs_2;

    thing is that I want to sort a vector by sort_var.
    How can I do that?

    Regards,
    Philia
  • Laharl
    Recognized Expert Contributor
    • Sep 2007
    • 849

    #2
    You can overload operator< to return based on that value, or write a function that takes two kurs inputs and returns one < other based on that variable. Then, you can call sort() from #algorithm and bingo, it's sorted. Note that using the second option requires using the three-parameter sort with the function name as the third argument.

    Comment

    • Philia
      New Member
      • Dec 2007
      • 5

      #3
      Thank you for reply.

      I made it this way:
      Code:
      class sorting
      {
      
      public:
      
          bool operator() ( const kurs & s, const kurs & t)
      
          {
      
              return s.wspolczynnik_sort < t.wspolczynnik_sort;
      
          }
      
      };
      ...
      Code:
      std::sort(kursy_2.begin(),kursy_2.end(),sorting());
      Hope it will be helpful to someone :)

      Regards,
      Philia

      Comment

      Working...