在C++中按成员按字母顺序对对象列表进行排序
Alphabetically sort a list of objects by member in C++
我正在尝试创建一个函数,按姓名或姓氏对通讯簿中的联系人列表进行排序。
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());
相关文章:
- C++ 创建包含链表和字符串的对象的链接列表时出错
- 我使用向量来创建类对象列表.初始化向量时如何使用参数调用构造函数?
- 从封装在对象中的函数 C++ 返回时为空的列表
- 如何在不销毁对象的情况下返回对象列表
- 如何使用Q_PROPERTY公开自定义对象列表
- 链接列表在 cpp 中包含不同的对象类
- 如何使用对象制作分数列表并获得平均值
- 什么更好?返回对象指针列表?或返回指向对象列表的指针?
- 如何将成员函数作为参数传递并在派生对象上执行方法列表
- 我可以从列表中获取对象并复制它们,但如何删除我复制的对象?
- 如何获取列表的每个对象并调用getName方法来打印其名称
- 如何在Windows Media Foundation SDK中指定语言列表对象
- 在 DLL 中嵌入 Python:Py_DECREF列表对象时访问冲突读取位置
- 将类的每个实例添加到列表对象的构造函数
- 列表<对象*>迭代器中的分段错误
- 如何使用list::sort()对STL列表对象进行排序,同时将自定义排序函数作为参数传递给list::排序
- 如何防止客户端修改列表对象
- c++列表对象错误
- 在列表对象中使用对象的派生函数
- 编译器错误 使用列表<对象*的迭代器> C++