如何在 C++ 中按字母顺序排序

How to sort by Alphabetical in C++

我一直在尝试使用名为姓氏的字符串数据成员对 Employee 的向量进行排序。我尝试了几种不同的方法,使用向量的排序方法,尝试将我的向量转换为列表并使用它的排序,我什至尝试使用字符串比较和 > 运算符,如下所示:

    vector<Employee>sortE(vector<Employee>record)
{
    for (unsigned int i = 0; i < record.size() - 1; i++)
        if (record[i].getLastName() > record[i+1].getLastName())
            swap(record[i], record[i + 1]);
    return record;
}

我想如果我将上面的方法与交换功能一起使用,它会起作用。但也许因为 swap 是一个字符串方法,而我正在用 Employees 做它不会正确交换?但我也用自己的 "swap" 尝试过,如下所示:

vector<Employee>sortE(vector<Employee>record)
{
    Employee temp;
    for (unsigned int i = 0; i < record.size() - 1; i++)
        if (record[i].getLastName() > record[i + 1].getLastName())
        {
            temp = record[i];
            record[i] = record[i + 1];
            record[i + 1] = temp;
        }

    return record;
}

无论哪种方式,我似乎都无法让它正常工作,任何见解或帮助将不胜感激。

您可以向 std::sort 提供一个 lambda:

std::vector<Employee> ve;
using std::begin;
using std::end;
std::sort(begin(ve), end(ve),
          [](const Employee& lhs, const Employee& rhs)
          {
              return lhs.getLastName() < rhs.getLastName();
          });

也就是说,在现实生活中,姓氏不一定是唯一的,当它们比较相等时,最好返回名字,如果这也等于其他字段,例如员工 ID:

              return lhs.getLastName() < rhs.getLastName() ||
                     lhs.getLastName() == rhs.getLastName() &&
                     (lhs.getFirstName() < rhs.getFirstName() ||
                      lhs.getFirstName() == rhs.getFirstName() &&
                      lhs.getId() == rhs.getId());

如果使用 C++11 或更新版本,您可以尝试使用 lambda(另外,我不知道您的 Employee class 长什么样,所以我做了一个简单的)。另外,在线执行检查这里:http://cpp.sh/6574i

#include <algorithm>
#include <iostream>
#include <string>
#include <vector>

class Employee
{
public:
    Employee( const std::string& firstName, const std::string& lastName ) :
        _firstName( firstName ),
        _lastName( lastName )
    {}

    ~Employee()
    {}

    std::string FirstName() const
    { 
        return _firstName;
    }

    std::string LastName() const
    {
        return _lastName;   
    }

    std::string FullName() const
    {
        return _firstName + " " + _lastName;   
    }

private:
    std::string _firstName;
    std::string _lastName;
};

int main()
{
    Employee e1( "Suresh", "Joshi" );
    Employee e2( "Mats", "Sundin" );
    Employee e3( "Steve", "Nash" );
    std::vector< Employee > employees { e1, e2, e3 };

    std::sort(employees.begin(), employees.end(), 
        [](const Employee& lhs, const Employee& rhs) -> bool
        { 
             return rhs.LastName() > lhs.LastName(); 
        });

    for ( auto employee : employees )
    {
        std::cout << employee.FullName() << std::endl;
    }
}