简体   繁体   中英

qsorting an array of class pointers

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.

You have used list->size instead of list->size() . The code should be:

qsort(list->list, list->size(), sizeof(String**), compare);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM