I've read a lot of material on how to do this. Unfortunately, they all resort to using something other than qsort (sort, usually). However, this is impossible for me as I'm not allowed to use anything from the algorithm library. I have to implement this from scratch, pretty much. What I've got:
class String {
public:
char* string;
int size;
String(char* string=0, int size=0) {
this->string = string;
this->size = size;
}
~String() {
delete [] string;
}
};
int compare(void* obj1, void* obj2) {
String* str1 = ((String*) obj1)->getColumn(column);
String* str2 = ((String*) obj2)->getColumn(column);
int i = strcmp(str1->string, str2->string);
delete str1;
delete str2;
return i;
}
class ArrayList {
int count;
int arraySize;
public:
String** list;
ArrayList() {
count = 0;
arraySize = 10;
list = new String*[arraySize];
}
~ArrayList() {
while(size()) {
delete remove();
}
}
void add(String* s) {
if(count==arraySize)
grow();
list[count++] = s;
}
String* remove() {
return list[count--];
}
String* get(int i) {
return list[i];
}
int size() {
return count;
}
private:
void grow() {
String** temp = new String*[arraySize*=2];
for(int i=0; i<count; i++) {
temp[i] = list[i];
}
delete [] list;
list = temp;
}
};
And my (current) call to qsort, though I've tried many combinations:
qsort(list->list, list->size, sizeof(String**), compare);
The error I ALWAYS get, not matter what I pass:
argument of type ‘int (ArrayList::)()’ does not match ‘size_t’
The code I've copied here doesn't include everything, but I've verified that all of the pieces work as intended, so don't worry about missing methods and such.
qsortis exactly likestd::sort, except for some nasty casts that serve no purpose but to cause needless confusion in students.const. I haven't struggled with C++ very much, for some reason I just couldn't see thesizeissue. On the other hand, I already know PHP and Java, and have dealt with a bit of C before, but it was for a specific embedded system. I think you all have a little lack of faith in students :)