排序std :: list< myclass *> with myclass :: operator<(myclass& other) [英] Sort a std::list<myclass*> with myclass::operator<(myclass &other)

查看:153
本文介绍了排序std :: list< myclass *> with myclass :: operator<(myclass& other)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 std :: list< myclass *> ,在我的类中有 myclass :: operator<(myclass& other )定义。

I have a std::list<myclass*> and in my class I have myclass::operator<(myclass &other) defined.

我使用 std :: list.sort() ,但它不会更改该列表中的任何内容。也许它只是排序指针?

I use the std::list.sort() function, but it does not change anything in that list. Maybe it just sorts the pointers?

如何排序列表中的实际项目?

How can I sort the actual items in that list?

推荐答案

您正在排序指针值,而不是myclass值。您必须通过引用来编写自己的谓词来比较指针:

You are sorting the pointer values, not the myclass values. You have to write your own predicate to compare pointers by dereference:

template <typename T> bool PComp(const T * const & a, const T * const & b)
{
   return *a < *b;
}

std::vector<Foo*> myvec;
std::list<Foo*> mylist;
std::sort(myvec.begin(), myvec.end(), PComp<Foo>);
mylist.sort(PComp<Foo>);

顺便说一下,我想你不能排序 std :: list std :: sort 来自< algorithm> ,因为它不是随机访问。使用成员函数 sort 而不是MerickOWA说。 (但是这通常不如排序随机访问容器有效。)或者,你可以立即存储你的对象在一个有序的容器如 std :: set< Foo *,PPred> ,其中 PPred 是谓词的函子版本:

By the way, I think you cannot sort std::list with std::sort from <algorithm> because it is not random access. Use the member function sort instead as MerickOWA says. (But that's generally less efficient than sorting a random-access container.) Alternatively, you can immediately store your objects in a sorted container like std::set<Foo*, PPred>, where PPred is the functor version of the predicate:

struct PPred {
  template <typename T> inline bool operator()(const T * a, const T * b) const
  { return *a < *b; }
};

这篇关于排序std :: list&lt; myclass *&gt; with myclass :: operator&lt;(myclass&amp; other)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆