按一个字段对自定义对象向量进行排序
Sorting a vector of custom objects by one field
如果有一个结构:
#include <algorithm>
#include <vector>
#include <iomanip>
#include <string>
using namespace std;
bool pred(string *a, string *b){
return *a < *b;
}
struct Student {
int ID;
int age;
double gpa;
string firstname;
string lastname;
};
int main () {
vector<Student*>v;
vector<Student*>v_sortedFirstName;
//both filled with same information
// sort v_sortedFirstName by first name
sort(v_sortedFirstName.begin(), v_sortedFirstName.end(), pred);
}
现在假设向量v
被填充有信息,而v_sortedFirstName
被填充有相同的信息(指向与v
相同的点)。如何(使用STL排序函数,按名字对v_sortedFirstName
进行排序?
我在想这句话:sort(v_sortedFirstName.begin(), v_sortedFirstName.end(), pred);
应该是类似sort(v_sortedFirstName->firstname.begin(), v_sortedFirstName->firstname.end(), pred);
的东西,但这不起作用。
另外,如果你们不介意的话,我想坚持上面的谓词函数,不要使用Lambda,因为我还没有学会。
谓词必须接受Student *
而不是string *
:
bool pred(Student *a, Student *b){
return a->firtname < b->firtsname;
}
注意,如果您不打算将数据更改参数类型修改为const Student *
,这将使您的代码更干净、更安全(如果您将代码放在pred
中,错误地尝试修改该结构,则编译器将拒绝编译,并且很容易检测并修复该错误):
bool pred(const Student *a, const Student *b){
return a->firtname < b->firtsname;
}
相关文章:
- 自定义对象的dlib序列化在gcc中失败
- 如何将带有自定义对象的容器从C++传递到QML
- 将 exprtk 与自定义类的对象一起使用
- 将 RTOS 队列对象封装在仅具有静态分配的 IQueue 自定义接口中
- 如何实现自定义匹配器以检查 Catch2 中的对象相等性
- 如何使用Q_PROPERTY公开自定义对象列表
- Qt5 远程对象 + 自定义类型,但不在 POD 中
- 从自定义类获取对象向量中的 max 元素
- 如何将来自 Boost.Python 的map_indexing_suite与自定义而不是标准对象一起使用?
- 如何在自定义对象的<<运算符中添加自定义前缀
- 如何使用 STL 排序对具有模板专用化的自定义类对象进行排序?
- 如何从 cpp 中的函数返回自定义类对象?
- 如何为自定义模板对象创建专门的函数模板
- 带有自定义deleter的std::unique_ptr对象的大小(一个由ref捕获的lambda)
- 基于3个对象的自定义排序
- 如何键入用于const对象的自定义io操纵器
- 指向临时对象的自定义迭代器(延迟加载)
- 将自定义对象作为参数从目标 C 传递到 C++
- 从 Arduino 中的自定义C++库构造对象时出错
- 从链表访问对象(自定义实现)