Ok basically, I'm trying to sort by class definition in c++.
For example I have a class:-
class crap
{
private:
string word;
int word_length;
...
Which gets words from a list and then sorts them by word length or in alphabetical order. However, I couldn't find anything useful. :cry: :cry: :eek: :cool: :rolleyes:
I found something using structs in c however, I want to do this is c++.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define NELEMS 4
struct crap
{
char word[163];
int word_length;
};
static int name_comp(const void *, const void *);
static int word_length_comp(const void *, const void *);
int main()
{
size_t i;
static struct crap stuff[NELEMS] =
{{"yo",2},
{"momma",5},
{"iz",2},
{"phat",4}};
qsort(stuff, NELEMS, sizeof stuff[0],
name_comp);
puts("By alphabetical order:");
for (i = 0; i < NELEMS; ++i)
printf("%s, %d\n",
stuff[i].word,
stuff[i].word_length);
qsort(stuff, NELEMS, sizeof stuff[0],
word_length_comp);
puts("\nBy word length:");
for (i = 0; i < NELEMS; ++i)
printf("%s, %d\n",
stuff[i].word,
stuff[i].word_length);
getchar();
getchar();
return 0;
}
static int name_comp(const void *p1, const void *p2)
{
struct crap *sp1 = (struct crap *) p1;
struct crap *sp2 = (struct crap *) p2;
int order = strcmp(sp1->word,sp2->word);
return order;
}
static int word_length_comp(const void *p1, const void *p2)
{
struct crap *sp1 = (struct crap *) p1;
struct crap *sp2 = (struct crap *) p2;
return sp1->word_length - sp2->word_length;
}
God bless.