red_coder's blog

By red_coder, 12 years ago, In English

suppose a class is as follows.. class cool { public: int a; int b; }; cool A[100];

now each element of array A[] has two sub elements 'a' and 'b'. Suppose we want to sort the array A[] in increasing order of 'a' and if two elements have equal 'a' then element with greater 'b' should be before. Can anyone give me the c++ code for the above purpose....

  • Vote: I like it
  • +5
  • Vote: I do not like it

»
12 years ago, # |
Rev. 2   Vote: I like it +9 Vote: I do not like it

inline bool operator < (const cool& A, const cool& B) {return A.a < B.a || (A.a == B.A && A.b < B.b);}

And then you can simply write:

sort(A, A + 100);

  • »
    »
    12 years ago, # ^ |
      Vote: I like it 0 Vote: I do not like it

    hey DimaPhil please tell me one thing , while coding the best sorting method that should be used is simple sort() function or any other

    • »
      »
      »
      12 years ago, # ^ |
        Vote: I like it +1 Vote: I do not like it

      I think yes, but I'm not sure.

      This method can also be useful:

      inline bool Less(cool A, cool B) { return A.a < B.a || (A.a == B.a && A.b < B.b); }

»
12 years ago, # |
  Vote: I like it +1 Vote: I do not like it
»
12 years ago, # |
  Vote: I like it +7 Vote: I do not like it
  • »
    »
    12 years ago, # ^ |
      Vote: I like it 0 Vote: I do not like it

    thanks a lot DAIe , your code cleared my doubt. Can u please give me a link so that i can read more about these types of operations