assignment, must use qsort in member function. help.

The help I need isn't with using qsort, so much as it's using the compare function. I've done it with if else statements, with compare from string class, everything compiles with no errors, but my array isn't being sort, here is what I have. I do have to use qsort for this. So I'm stuck there. But I've been following this in the debugger and can't see what's going wrong. If you need all the code let me know and I'll post.

I do however know, that it's something wrong with my compare function, I'm 95.99% sure.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
#include  <iostream>
#include  <fstream>
#include  <string>
#include  <cstring>
#include  <cstdlib>
#include  <iomanip>

#include  "dict.h"


using namespace std;

Dictionary::Dictionary(const char *filename)
{
ifstream  in(filename, ios::in);

  if  (in.fail())
  {
    cout  <<  "Error, file failed to open: "
          <<  filename
          <<  endl;
  }

in >> wordNum;

get_memory();
load_array(in);
sort_array();

}

int Dictionary::compare( const void  *vp1, const void  *vp2 )
{
  words_def  *p1  = (words_def *)  vp1;
  words_def  *p2  = (words_def *)  vp2;

//  if (p1->word > p2->word) {return 1;}
//  if (p1->word < p2->word) {return -1;}
//  return 0;
 return p1->word.compare(p2->word);
}

void Dictionary::sort_array()
{
qsort( word_def_array , wordNum , sizeof(words_def) , compare);
show_array();
}

void Dictionary::load_array(ifstream &in)
{
 for (int inc = 0 ; inc < wordNum ; ++ inc)
  {
     getline ( in, word_def_array[inc].word, ',');
     getline ( in, word_def_array[inc].define);
     cout << word_def_array[inc].word   << endl;
     cout << word_def_array[inc].define << endl;
  }
in.close();
}

void Dictionary::show_array()
{
for (int inc = 0 ; inc < wordNum ; ++ inc)
  {
     cout << word_def_array[inc].word   << endl;
     cout << word_def_array[inc].define << endl;
  }
}

void Dictionary::get_memory()
{
word_def_array = new words_def[wordNum];  // Delete in destructor

if  (! word_def_array){
    cout  <<  "Failed to allocate memory."  <<  endl;
    exit( EXIT_FAILURE );
    }
}

Dictionary::~Dictionary()
{
  delete [] word_def_array;
}


here is the struct I'm using in the header file under private:
1
2
3
4
struct words_def{
  string word;
  string define;
  };


Any feedback is appreciated!
Last edited on
Topic archived. No new replies allowed.