在c ++中排序struct数组

时间:2014-01-01 05:00:44

标签: c++ arrays sorting struct

我有一个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;
}

2 个答案:

答案 0 :(得分:5)

这段代码可以是许多好方法中的一种方法。我只使用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]); 
});

答案 1 :(得分:1)

#include <iostream>
#include <algorithm>

using namespace std;

struct user
{
    char lname[30];
    int userid;
};

user libuser[1000];
int elementCount = 0;

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;

    //sort
    for(int i = 0; i < 1000; i++)
    {
        for(int j = 0; j < 1000 - 1; j++)
        {
            if(strcmp(libuser[j].lname, libuser[j + 1].lname) > 0)  //change to < 0 for descending sort
            {
                user temp = libuser[j];
                libuser[j] = libuser[j + 1];
                libuser[j + 1] = temp;
            }
        }
    }


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


    system("PAUSE");

    return 0;
}