我有一个Struct数组,尝试按lname按字母顺序对它们进行排序,我尝试了冒泡排序,但是当我们数组中有一些空项目时,冒泡排序将无法正常工作。因此,有没有函数可以对这些项进行排序?

这是我的代码:

#include<iostream>
#include<algorithm>

using namespace std;


struct user {

char lname[30];
int userid;
};

user libuser[1000];

int main(){


strcpy(libuser[0].lname,"");
libuser[0].userid = 0;


strcpy(libuser[1].lname,"backzade");
libuser[1].userid = 1;

strcpy(libuser[2].lname,"akhondali");
libuser[2].userid = 2;

    strcpy(libuser[3].lname,"sayidian");
libuser[3].userid = 3;

    strcpy(libuser[4].lname,"navah");
libuser[4].userid = 4;

    strcpy(libuser[5].lname,"mostarab");
libuser[5].userid = 5;


libuser[6].userid = 0;


    strcpy(libuser[7].lname,"");
libuser[7].userid = 0;

    strcpy(libuser[8].lname,"");
libuser[8].userid = 0;

    strcpy(libuser[9].lname,"borobaba");
libuser[9].userid = 9;

    strcpy(libuser[10].lname,"divune");
libuser[10].userid = 10;



for(int i=1;i<1000;i++)
    if(libuser[i].userid!=0)
        cout<<libuser[i].lname<<"\n";


system("PAUSE");

return 0;
}

最佳答案

这段代码只是许多好的方法中的一种。我只使用std::sort和lambda。
希望对您有所帮助。新年快乐!

std::sort (std::begin(libuser), std::end(libuser), [&](const user& first, const user& second) -> bool
{
    return (first.lname[0] < second.lname[0]);
});

09-16 19:23