C++ 使用Sort()算法c+对对象列表进行排序+;
我在对对象列表使用排序算法时遇到问题。这是我的密码C++ 使用Sort()算法c+对对象列表进行排序+;,c++,algorithm,sorting,C++,Algorithm,Sorting,我在对对象列表使用排序算法时遇到问题。这是我的密码 #include <iostream> #include <string> #include <list> //#include <iterator> //#include <functional> #include <algorithm> using namespace std; class Project { private: string name;
#include <iostream>
#include <string>
#include <list>
//#include <iterator>
//#include <functional>
#include <algorithm>
using namespace std;
class Project
{
private:
string name;
int days;
public:
Project(string n, int d)
{
name = n;
days = d;
}
int get_days() const
{
return days;
}
void show() const
{
cout << "Name of the project: " << name << endl;
cout << "Days to completion: " << days << endl;
cout << endl;
}
};
static bool sortByAge(const Project &lhs, const Project &rhs)
{
return lhs.get_days() < rhs.get_days();
}
int main()
{
list<Project> l1, l2;
Project ob1("Alpha", 120), ob3("Gama", 60), ob5("Omega", 200);
l1.push_back(ob1);
l1.push_back(ob3);
l1.push_back(ob5);
sort(l1.begin(), l1.end(), sortByAge);
cout << "LIST 1" << endl;
for (const auto& p : l1)
{
p.show();
}
system("pause");
}
#包括
#包括
#包括
//#包括
//#包括
#包括
使用名称空间std;
班级项目
{
私人:
字符串名;
国际日;
公众:
项目(字符串n,整数d)
{
name=n;
天数=d;
}
int get_days()常量
{
返程天数;
}
void show()常量
{
问题是std::sort
需要随机访问迭代器,但是std::list
不提供它们;它只支持双向迭代器。这就是为什么std::list
有自己的sort
成员函数的原因。因此,不要调用std::sort(l1.begin()、l1.end()、sortByAge)
调用l1.sort(sortByAge)
std::sort
接受RandomAccessIterator
s
template< class RandomIt >
void sort( RandomIt first, RandomIt last );
欢迎使用Stack Overflow!请将您的代码粘贴到您的问题中,形成一个标签,这样在hastebin从Internet上消失很久之后,它可能对其他人有用。请阅读欢迎使用标签。请不要通过其他网站的链接或图片引用您的标签。您的帖子的读者在您的帖子中看到它要方便得多。F另外,请避免复制/粘贴整个程序。您应该只参考几行代码,其中您已经粘贴了。最后但并非最不重要的是,请访问上面Fred提到的链接。它非常有用。重新打开。这是一个关于如何对向量排序的问题的副本。这个问题是关于列表的。@Christos:There's q如果问题不包含完整的程序,则很有可能会以主题外的形式结束-但是海报需要尝试尽可能减少程序。在这种情况下,不需要默认构造函数,不需要set_name、get_name和set_days函数,不需要ob2和ob4,最后是li不需要注释它们。
template< class RandomIt >
void sort( RandomIt first, RandomIt last );
l1.sort(sortByAge);