Hello People, I've joined this forum and I need some help with sorting a vector of structures. Here is the problem:
I have the following structure>
struct student
{
char name[20];
char lastname[20];
int points;
} class[10];

Can you help me figuring out a void function that will have a struct student vector (or its reference) as an input element, and some other number, int n (in this case 10), that will sort the vector class[10] by lastname? :idea:
Thanks

You could use any of the regular sort functions. Your comparison must be correctly done, as in

if( strcmp( my_class[i].lastname, my_class[i+1].lastname) > 0 )

which is the comparison for bad ol' bubble sort.

I changed the array name as "class" is a reserved word. And you have an array, not a vector.

Hello People, I've joined this forum and I need some help with sorting a vector of structures. Here is the problem:
I have the following structure>
struct student
{
char name[20];
char lastname[20];
int points;
} class[10];

Can you help me figuring out a void function that will have a struct student vector (or its reference) as an input element, and some other number, int n (in this case 10), that will sort the vector class[10] by lastname? :idea:
Thanks

Thanks vmanes so much. I really thought that strcmp just tells which array is longer, and i don't have a vector, as well, so thank you for that too
Before i wrote the strcmp code, i had written the following code>

void sort(student a[],int n)
{
     student s;
     for(int i=0;i<n;i++)
     for(int j=0;j<n-i-1;j++)
     for(int k=0, int m=0;k<strlen(a[j].lastname),m<strlen(a[j+1].lastname);k++,m++)
     {
         if(a[j].lastname[k]<a[j+1].lastname[m]) {flag=1;break;}
         else flag=0;
         
         if(flag==0)
         if(a[j].lastname[k]>a[j+1].lastname[m]) 
        { s=a[j];
          a[j]=a[j+1];
          a[j+1]=s;
        } else continue;
     }
         
}

Thanks once again 4 the help, but does this code look like it can do the sorting job aswell? (it's just matter of my personal satisfaction) :)
Salut

Thanks once again 4 the help, but does this code look like it can do the sorting job aswell? (it's just matter of my personal satisfaction) :)
Salut

Why are you asking? Does it work? If not, no. If so, yes.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.