[英]Searching/Ordering Linked Lists Based on Class Member (C++)
我有一个正在创建的程序,其中涉及使用链接列表存储我的数据。 这是节点和列表类的定义:
template<class T>
struct Node{
T data;
Node *link;
};
template<class T>
class LinkedList{
private:
Node<T> *head;
public:
LinkedList(){
head = NULL;
}
};
我有不同的类(例如人员,项目等),每个类都有自己的列表。 我希望能够基于类的成员对这些列表进行排序,但是我不确定如果没有大量不同的排序功能,如何执行此操作。
我来自C#背景,其中LINQ允许类似以下内容:
PersonList.OrderBy(x=>x.LastName)
该列表将根据Person类的姓氏对列表进行排序。
我希望能够在C ++中执行类似的操作,但是我仍然对这种语言持绿色态度,并且不确定会带来什么。
如果您想使用自制的链表类,则需要一般性地编写排序,并且只能根据“交换”条件对其进行更改。 这是它的外观模型(注意-未编译,请原谅任何语法错误):
template<class T>
class LinkedList{
private:
Node<T> *head;
typedef bool (*cmpFunc)(T &a, T &b);
public:
LinkedList(){
head = NULL;
}
void Sort(cmpFunc)
{
T* item1, *item2;
// whatever sorting routine you choose, doesn't matter.
//...
// now we are at the point in our routine where we need to compare two items
if ( !cmpFunc(*item1, *item2) )
{
// we swap item1 and item2's position since the comparison
// function says that item1 should come after item2 (the return
// of false did this).
}
}
};
class Person
{
int age;
public:
int getAge() const { return age; }
Person(int n = 1) : age(n) {}
};
...
bool CompFunction(int& i1, int& i2)
{
return i1 > i2; // return true if i1 > i2, false otherwise
}
bool personComp(Person& p1, Person& p2)
{
return p1.getAge() < p2.getAge(); // sort on the age (for example)
}
LinkedList<int> l1;
//... fill it with values
l1.Sort(&CompFunction); // will sort the ints in descending order
LinkedList<Person> p;
//... fill p with Person objects
p.Sort(&personComp); // sorts person based on age in ascending order
请注意,我没有为您提供排序例程,算法等。要点是,无论您选择哪种排序算法或例程,当涉及到两项比较时,您cmpFunc
使用这两项来调用用户定义的cmpFunc
函数项目。
因此,用户为您提供了功能,并且在该功能中进行了自定义比较。 如果函数返回true
则传递的参数顺序正确,否则返回false
。 交换例程检查返回值,如果返回false
则交换项目。
请注意,这是一个粗略的设计,但它演示了在需要使用不同条件时如何实现交换功能的基本要点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.