Using std::sort

I am using a array of pointers to objects and wish to sort them using std::sort(). However, I've noticed that sort() cannot do this and seems to only work on non-pointer arrays.

Is there a way I can keep the array of pointers and somehow make std::sort work?

Sample code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// working version
#include <algorithm>
using namespace std;

int main()
{
	int Ar[] = {5,1,2,4};
	sort( Ar, Ar+sizeof(Ar)/sizeof(int) );

	return 0;
}

// Non working version - This is what I want to get working
#include <algorithm>
using namespace std;

int main()
{
	int Ar[] = { new int(5), new int(1), new int(2), new int(4) };
	sort( Ar, Ar+sizeof(Ar)/sizeof(int*) );

	return 0;
}
In this case you are sorting pointers by their addresses.
I am interested in what do you expect from this sorting?
You can provide your own compare function as third parameter to sort. Try something like this:

1
2
3
4
5
6
bool derefLess(int* i1, int* i2)
{
    return *i1 < *i2;
}
...
    sort(Ar, Ar+sizeof(Ar)/sizeof(int*), derefLess);

Awesome, thanks imi.

Denis
I should have realized that was what it was doing but didn't connect the dots.
Topic archived. No new replies allowed.