🚀 go-pugleaf

RetroBBS NetNews Server

Inspired by RockSolid Light RIP Retro Guy

Article View: gnu.g++.help
Article #755

Re: g++ and qsort

#755
From: Don &
Date: Wed, 30 Aug 1995 00:53
45 lines
1801 bytes
The original message from amgaudra that apparently started this
thread has expired at our site.  So the following may or may not
answer the question.  The code below works with gcc-2.7.0 on a
Sparc.  It allows one to access qsort in a relatively type-safe
way.  "Relatively" because there is still a function pointer
cast used, but at least it is just in one place.  Probably it
would be best to use one of the new types of casts recently added
to the language, but I haven't learned that stuff yet.

Don Bashford
bashford@scripps.edu


// A template wrapper around the C library qsort function
#include <stdlib.h>

template<class T>
void myqsort(T* base, size_t nmemb, int (*Compar)(const T*, const T*) )
{
  typedef int (*PFC)(const void*, const void*);
  PFC compfun = (PFC) Compar;
  size_t size = sizeof(T);
  qsort (base, nmemb, size, compfun);
}

// ----- Stuff above here could be in a header file.  Below is application.

#include <iostream.h>

int mycomp(const int* i, const int* j)
{
  return *i - *j;
}

main()
{
  int a[3];
  a[0] = 6;
  a[1] = 2;
  a[2] = 4;
  myqsort(a, 3, mycomp);
  cout << "a contains ";
  for (int i=0; i<3; ++i) cout << a[i] << " ";
  cout << endl;
}
Technical Details
Message-ID: <BASHFORD.95Aug29175315@toad.scripps.edu>
Path: arc1-ca.pugleaf.net!scripps.edu!bashford
References: <DDpG3H.88M@watserv3.uwaterloo.ca> <41l6h3$cus@news2100.microsoft.com>

Show Full Headers
Complete Article Headers
Path: arc1-ca.pugleaf.net!scripps.edu!bashford
From: bashford@toad.scripps.edu (Don &)
Newsgroups: gnu.g++.help,comp.lang.c++
Subject: Re: g++ and qsort
Date: 30 Aug 1995 00:53:15 GMT
Organization: The Scripps Research Institute, La Jolla, CA, USA
Message-ID: <BASHFORD.95Aug29175315@toad.scripps.edu>
References: <DDpG3H.88M@watserv3.uwaterloo.ca> <41l6h3$cus@news2100.microsoft.com>
NNTP-Posting-Host: toad.scripps.edu
Mime-Version: 1.0
Content-Type: text/plain; charset=us-ascii
Content-Transfer-Encoding: 7bit
In-reply-to: a-cnadc's message of 25 Aug 1995 18:58:43 GMT