按结尾排序第一个名称

Joe*_*Joe 1 c++ sorting struct

我有按姓氏排序的算法,但我无法弄清楚如何按姓氏排序,然后如果两个人有相同的姓氏,按他们的名字排序.

void sortLastName(FRIEND friends[ARRAY_MAX], int& count) {

    FRIEND temp;

    for(int i = 0; i < count - 1; i++) {
        for (int j = i + 1; j < count; j++) {
            if (stricmp(friends[i].lastName, friends[j].lastName) > 0)  {
                temp = friends[i];    //swapping entire struct
                friends[i] = friends[j];
                friends[j] = temp;
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

===编辑====================

我不想用 STD sort()

jal*_*alf 9

你为什么不用std::sort?这就是它的用途:

struct NameComparer {
  bool operator()(const FRIEND& lhs, const FRIEND& rhs){
    int compareResult = stricmp(lhs.lastName, rhs.lastName);
    if(compareResult == 0){
      compareResult = stricmp(lhs.firstName, rhs.firstName);
    }
    return compareResult < 0;
  }
};

std::sort(friends, friends + ARRAY_MAX, NameComparer());
Run Code Online (Sandbox Code Playgroud)

当然,你也应该使用C++ std::string类.这就是它的用途.然后你不必使用容易出错的C字符串操作函数stricmp.

  • 你显然不想使用C++字符串或向量.让我想知道为什么你不只是称它为C. :) (6认同)

Ada*_*eld 5

首先,比较姓氏.如果它们相等,那么比较名字:

int compareResult = stricmp(friends[i].lastName, friends[j].lastName);
if(compareResult == 0)
    compareResult = stricmp(friends[i].firstName, friends[j].firstName);
if(compareResult < 0)
    // swap friends[i] and friends[j]
Run Code Online (Sandbox Code Playgroud)