我正在尝试创建一个函数来按名称或姓氏对地址簿中的联系人列表进行排序.
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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
我确定我没有正确地做到这一点,但我对这些迭代器有点失落.我也知道我应该有另一个while循环遍历所有联系人,直到所有联系人都被排序,但老实说我不知道如何实现它.
std :: list有一个重载的成员函数sort,即
按升序对元素进行排序.保证保持相等元素的顺序.第一个版本使用operator <来比较元素,第二个版本使用给定的比较函数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(); }
};
Run Code Online (Sandbox Code Playgroud)
或更简单的免费功能
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(); }
Run Code Online (Sandbox Code Playgroud)
你也称之为
address_book.sort(sort_by_name());
address_book.sort(sort_by_last_name());
Run Code Online (Sandbox Code Playgroud)
要么
address_book.sort(cmp_by_name);
address_book.sort(cmp_by_last_name);
Run Code Online (Sandbox Code Playgroud)
访问器get_name()和get_last_name()必须是const.