在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.