提问者:小点点

如何按字母顺序对联系人进行排序?


如何将输入的联系人按字母顺序排序并显示? 我试过几种方法,但到目前为止都没有成功。 任何形式的帮助都将不胜感激!

使用名称空间标准;

struct contact{
    char name[50];
    int number;

};

contact cont[50];

void add_new_contact(){
    int getNum;
    for (int i=0;i<50;i++){
        cout << "Enter contact name: ";
        cin >> cont[i].name;
        cout << "Enter contact number: ";
        cin >> cont[i].number;

        cout << "Would you like to add another contact?\n";
        cout << "1.  Yes\n";
        cout << "2.  No\n";
        cout << "Choice: ";
        cin >> getNum;
        if (getNum == 2)
            break;
        else
            continue;
    }

}

void sort_in_alphabetical_order(){
    int i,j;
    char temp[50];
    for (i = 0; i < 50; i++) {
            if (cont[i].name[0] > cont[i+1].name[0]) {
                temp[50] = cont[i].name[50];
                cont[i].name[50] = cont[i+1].name[50];
                cont[i+1].name[50] = temp[50];
                cout << cont[i+1].name << endl;

        }
    }

}

共1个答案

匿名用户

所有可能的方法之一:您可以使用std::sort和比较函数对象。 这里,它是一个lambda函数。

std::sort(cont, cont+sizeof(cont)/sizeof(*cont), [&](const contact& conA, const contact& conB){
    std::string A(conA.name), B(conB.name);
    return A < B;
});