在C ++中按成员按字母顺序对对象列表进行排序 [英] Alphabetically sort a list of objects by member in C++

查看:252
本文介绍了在C ++中按成员按字母顺序对对象列表进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个功能,以按姓名或姓氏对通讯录中的联系人列表进行排序.

I'm trying to create a function to sort a list of contacts in an address book by name or last name.

 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循环遍历所有联系人,直到对所有联系人进行排序为止,但是老实说,我不知道如何实现它.

I'm sure I'm not doing it correctly, but I'm a little bit lost with these iterators. I also know I should have another while loop to loop through all my contacts until all of them are sorted but, honestly I have no idea how to implement it.

推荐答案

std :: list具有重载的成员函数sort,即

std::list has an overloaded member function sort, that

按升序对元素进行排序.保证相等元素的顺序被保留.第一版本使用operator<为了比较元素,第二个版本使用给定的比较函数comp.

Sorts the elements in ascending order. The order of equal elements is guaranteed to be preserved. The first version uses operator< to compare the elements, the second version uses the given comparison function comp.

要提供比较功能,您可以使用功能键:

To give the comparison function you can use functors:

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);

访问器的get_name()和get_last_name()必须是const.

the accessors get_name() and get_last_name() must be const.

这篇关于在C ++中按成员按字母顺序对对象列表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆