Home > Mobile >  I want to sort an array of structures using templatized qsort
I want to sort an array of structures using templatized qsort

Time:11-07

I have an array containing pointers to objects. Each object has a data member called name of type string.

I want to sort it using the templatized qsort function. Note again that each element in the array is a pointer to an object. However, I get the error:

error C2227: left of '->name' must point to class/struct/union/generic type

at this line:

return strcmp(a->name, b->name);

on compile time.

Why I get this error?

Here is the full code (I work with Visual Studio 2019):

#include <cstdlib>
#include <stdio.h>
#include <string.h>
//----------------------------------------------------------------------
class my_type {
public:
    char name[10];
    my_type(char* source) {
        strcpy(name, source); // assume data are valid
    }
};
//----------------------------------------------------------------------
template <typename a_type>
int compare(const void* pa, const void* pb)
{
    a_type* a = (*(a_type**)pa);
    a_type* b = (*(a_type**)pb);

    return strcmp(a->name, b->name);
}
//----------------------------------------------------------------------
int main()
{
    my_type**a;
    int n = 5;

    a = new my_type * [n]; // allocate the array.

    for (int i = 0; i < n; i  ) {
        char buf[100];
        _itoa(i, buf, 10);
        a[i] = new my_type(buf); // allocate each element of the array.
    }

    qsort(a, n - 1, sizeof(a[0]), compare<my_type*>); // sort them

    for (int i = 0; i < n; i  )// print the sorted elements
        printf("%s ", a[i]->name);

    for (int i = 0; i < n; i  )
        delete a[i]; // delete each element
    delete[] a; // delete array

    getchar();
}
//----------------------------------------------------------------------

CodePudding user response:

name is a c string. Is there any reason why you do not use c strings from stdlib ? You won't be able to compile a code with a template ? Or std::sort ?

Anyway, the problem is that when you call the template, you define the type as a pointer. You end up with a pointer to pointer, which has no field "name".

  • Related