Sorting arrays of pointers using <algorithm> sort()

Write here if you have problems with your C++ source code

Moderator: Board moderators

Post Reply
drewsome
New poster
Posts: 16
Joined: Mon Dec 01, 2003 1:20 am
Contact:

Sorting arrays of pointers using <algorithm> sort()

Post by drewsome » Thu Jun 23, 2005 6:34 am

Hi everyone!

My question is pretty straightforward: I have an array of pointers that I would like to sort using the sort() function prvoided in <algorithm>. If it was an array of objects, I would do the following:

Code: Select all

#include <algorithm>

struct s {

   const bool operator<(const s other) const {
      return true;
   }

};

s sArray[10];

sort(sArray, 10);
OK, fine, no problem :) But what do I do when sArray doesn't hold objects, but pointers to objects?

Code: Select all

s *sArray[10]
Obviously operator< will not cut it. My solution so far has been to write a separate function to do the comparison and pass this in to sort():

Code: Select all

struct comparisonFunctor() {
  bool operator() (const s *s1, const s *s2) const {
    return true;
  }
}

s *sArray[10];

sort(sArray, 10, comparisonFunctor());
I would love to know if there are other ways to do this. Specifically, I want a way to be able to accomplish this without using comparisonFunctor.. is it possible to write an overloaded < operator that will sort pointers?

Thanks!
- Andrew

User avatar
Krzysztof Duleba
Guru
Posts: 584
Joined: Thu Jun 19, 2003 3:48 am
Location: Sanok, Poland
Contact:

Post by Krzysztof Duleba » Thu Jun 23, 2005 7:46 am

operator< must have an argument of class or enumerated type. This limitation holds even if operator< is declared outside of the class body - in this case if the first argument is a pointer, the second must not.

The other way you can do it is to write a functional object

Code: Select all

struct comparator{
    bool operator()(const s * s1, const s * s2){
          ...
    }
};

Post Reply

Return to “C++”