Archived

This topic is now archived and is closed to further replies.

MickeyMouse

Two questions on qsort()...

Recommended Posts

Hello everyone! My both questions relate standard qsort() from stdlib.h: 1. Does qsort() swap elements of given array or it allocates for sorting time another array of same size with elements of type "pointer to that type" and operates only on pointers when swapping? It's logic it would be much faster when you want to sort array of elements of type say int lala[100000] - swapping such elements would be very time consuming..... 2. How to do the following I want to have a class where I can put elements of templated type "Type" and sort them using qsort() passing in pointer to comparing function of same type as that for qsort. However I don't store my elements in "single" array (like int *Something), but in structure that contains additional marker "Used" of type boolean. So I'd like to have a class like this:
template (class Type) - proper brackets not supported here
class Just_Class
{

private:

	struct Element_t
	{
		Type ID;
		bool Used ;
	};

	Element_t *Elements;
	int Num;

	// Pointer to function comparing ID's of type "Type"
	int (*Cmp)(const void *, const void *);

	// Compares Elements
	static int CmpElements(const void *a, const void *b)
	{
		return (*Cmp)((const Element_t *)a->ID, (const Element-t *)b->ID);
	}

	public:

	// Constructors / Destructors...etc...
	// Put / Get element.....bla bla...etc

	// Sorts Elements
	void Sort(int (__cdecl *_Cmp)(const void *, const void *))
	{
		Cmp = _Cmp;
		qsort(Elements, Num, sizeof(Type), CmpElements);
	}

};
     
...but unfortunately this doesn't compile because CmpElements is static, so it can't call not static (*Cmp) (if I get it right)... When I don't make it static however there's no casting defined and qsort() says it can't accept 4th argument.... I solved this temporarily by putting this function pointer
int (__cdecl *Cmp)(const void *, const void *);
 
out of class but it's not elegant, is it? Any suggestions would be very appreciated... Thanks for any help. [edited by - MickeyMouse on October 16, 2002 9:30:47 AM]

Share this post


Link to post
Share on other sites