在C++中按成员按字母顺序对对象列表进行排序

Alphabetically sort a list of objects by member in C++

本文关键字:列表 对象 排序 C++ 成员 顺序      更新时间:2023-10-16

我正在尝试创建一个函数,按姓名或姓氏对通讯簿中的联系人列表进行排序。

 void sortList (list<Contact> & address_book){
 //define two iterators - first to point to the first element from the list, second to the second element
 list<Contact>::iterator it = address_book.begin();
 list<Contact>::iterator it2 = address_book.begin();
 it2++;
 //get the last name for the first 2 contacts
 string last_name1 = it->get_last_name();
 string last_name2 = it2->get_last_name();
 int i = 0;
 while (i < last_name1.length() && i < last_name2.length()){
       if (last_name1[i] < last_name2[i]){
          swap(it, it2);
          break;
       }
 }
}

我确信我做得不对,但我对这些迭代器有点迷失了方向。我也知道我应该有另一个while循环来循环我的所有联系人,直到所有联系人都被排序,但老实说,我不知道如何实现它。

std::list有一个重载的成员函数排序,即

按升序对元素进行排序。元素相等的顺序是可以保证的。第一个版本使用运算符<为了比较元素,第二个版本使用给定的比较函数comp。

要给出比较函数,可以使用函数

struct sort_by_name {
  bool operator()(const Contact &a, const Contact &b)
  { return a.get_name() < b.get_name(); }
};
struct sort_by_last_name {
  bool operator()(const Contact &a, const Contact &b)
  { return a.get_last_name() < b.get_last_name(); }
};

或更简单的免费功能

bool cmp_by_name(const Contact &a, const Contact &b)
{ return a.get_name() < b.get_name(); }
bool cmp_by_last_name(const Contact &a, const Contact &b)
{ return a.get_last_name() < b.get_last_name(); }

你称之为

 address_book.sort(sort_by_name());
 address_book.sort(sort_by_last_name());

 address_book.sort(cmp_by_name);
 address_book.sort(cmp_by_last_name);

访问器getname()和getlastname()必须是const。

不要自己排序。使用std::sort()。您需要提供一个自定义比较器——类似于以下内容:

struct LastNameComp {
    bool operator()(const Contact& a, const Contact& b) const {
        return a.get_last_name() < b.get_last_name();
    }
}
⋮
std::sort(address_book.begin(), address_book.end(), LastNameComp());

如果你可以使用C++11编译器,你可以做得更好:

std::sort(address_book.begin(), address_book.end(),
    [](const Contact& a, const Contact& b) {
        return a.get_last_name() < b.get_last_name();
    });

扩展使用std::lexicographical_compare给出的答案,并列出内部排序。

    struct LastNameComp {
        bool operator()(const Contact& a, const Contact& b) {
            return std::lexicographical_compare(
               a.get_last_name().begin(), a.get_last_name().end(),
               b.get_last_name().begin(), b.get_last_name().end(),  
            );
        }
    };
    address_book.sort(LastNameComp());