【发布时间】:2014-05-24 14:44:50
【问题描述】:
我已经成功地用文本文件中的数据填充了链表。链表包含structure,它有5 个string 类型的字段。
我希望按某个结构字段(升序或降序)对列表进行排序。我决定重载operator<,但我不知道如何实现。
到目前为止,我能够按一个固定字段对列表进行排序。以下是相关代码:
#include <iostream>
#include <list> // std::list
#include <fstream> // std::ifstream, std::ofstream
#include <string> // std::string
#include <algorithm> // std::remove, std::remove_if
#include <sstream> // std::istringstream
class Lista
{
private:
struct Person
{
// data from file
std::string lastName; // other fields omitted for keeping brevity
// operator < ( needed for correctly sorting the linked list )
bool operator< ( const Person &p )const
{
return lastName > p.lastName;
}
// constructor / destructor ... omitted for keeping brevity
};
// linked list that holds all the data from files
std::list<Person> persons;
public:
// constructor / destructor ... omitted for keeping brevity
// method for sorting the list
void sortList()
{
persons.sort();
}
};
我想添加enum 的选项,所以我可以使用只有一个 重载operator< 进行排序。
类似这样的:
class Lista
{
private:
struct Person
{
//================ here I could add enum of choices ============//
enum choice { FIELD1, LASTNAME, FIELD2 }; // you get the point
bool ascending; // decides if it is ascending or descending
//==============================================================//
// data from file
std::string lastName; // other fields omitted for keeping brevity
// operator < ( needed for correctly sorting the linked list )
bool operator< ( const Person &p )const
{
if ( choice == FIELD1 )
return field1 < p.field1;
if ( choice == FIELD2 )
return field2 < p.field2;
if ( choice == LASTNAME )
return lastName > p.lastName;
}
// constructor / destructor ... omitted for keeping brevity
};
// linked list that holds all the data from files
std::list<Person> persons;
public:
// constructor / destructor ... omitted for keeping brevity
// method for sorting the list
void sortList( Person::choice ch, bool ascending)
{
// here I should use the parameters to invoke proper sorting
persons.sort();
}
编辑:
我曾尝试将operator< 更改为函数但失败了:
// this function is inside of my private struct
bool compare( const Person &p1, const Person &p2 )const
{
return p1.lastName > p2.lastName;
}
然后我用这样的方法调用它:
void sortList()
{
persons.sort( compare );
}
但我收到以下错误:error C2065: 'compare' : undeclared identifier
我对如何做到这一点真的没有其他想法,你能帮我吗?
【问题讨论】:
-
除了重载
operator<加上if/switch,还可以提供一个比较器函数对象给list::sort。这可能会更快更简单。std::list::sort -
_Person_h_是为编译器保留的标识符。请不要使用任何以__或以_开头加大写字母的内容。 -
重复(作为 XY 问题):stackoverflow.com/q/9423480/420683
-
@dyp:我编辑了我的帖子,但尝试失败。我就是不知道出了什么问题,你能帮忙吗?谢谢。
标签: c++ sorting stl linked-list