Chinaunix首页 | 论坛 | 博客
  • 博客访问: 460461
  • 博文数量: 107
  • 博客积分: 6073
  • 博客等级: 准将
  • 技术积分: 790
  • 用 户 组: 普通用户
  • 注册时间: 2009-08-14 15:34
文章分类

全部博文(107)

文章存档

2010年(1)

2009年(106)

分类: C/C++

2009-10-06 23:12:47

作者:wangxinus,
来源:
http://wangxinus.cublog.cn
声明:原创文章欢迎转载,交流请Email给作者

今天写一段代码的时候,定义了一个list容器, 用来管理不定数目的对象,为了节约对象复制的时间,我保存的是对象的指针。

typedef std::list ObjectList;

然后我需要对这个链表进行排序,这时候我想到了sort算法。List自己提供了sort,最先我却用了algorithm中的sort, 却一直报错, 汗一下。 顺便说下, 我泛型算法用得不多。。。

std::list::sort() 用来对链表排序。然后需要greater() 或者 less()。但是他们的Type都应该是一个对象,我使用 greater 根本就没有排序。我也重载了

bool Object::operator>(const Object& obj) // 这里也有疑问,应该重载成这样,还是:

bool Object::operator>(const Object* obj)

最后我只有自己写了一个函数,但是我想应该有函数对象来解决的。但是对STL不熟悉,找了找,也没有找到。

template
bool GreaterPtr(Type* obj1, Type* obj2)
{
      return ( obj1->operator> ( *obj ) ); // 我重载的这个 bool Object::operator>(const Object& obj)
}

ObjectList objlist;
objlist.sort( GreaterPtr );

如何使用STL中自带的函数对象,比如 greater( ) 来对 包含对象指针的容器 进行排序呢????

阅读(1504) | 评论(4) | 转发(0) |
给主人留下些什么吧!~~

chinaunix网友2009-12-21 12:25:48

不要直接使用指针给LIST,用智能指针包装一下. 在list中sort时会调用greater,而greater,而将指针制定为容器持有类型的话,最终排序时候比较大小就会使用T.>(), 即(Object*).>(),而不是我们期望的(Object).>(),实际上即使你为Object重载了operator>()在排序中也不会被调用到, 导致的结构是你对list容器按指针到小了一遍序,而不是对指针所指对象的大小。 使用smart ptr包装。 举例来说,定义一个简单的SmartPtr(使用引用计数并不考虑多线程情况下): template smartptr { public: smartptr() { pThis = new T; m_pRecCount = new int; (*m_pRecCount)++; } // 拷贝构造函数,在stl中的一些运算会用到拷贝构造 smartptr(smartptr& t) { m_pThis = t.GetInterface(); m_pRecC

frischzenger2009-12-14 15:49:37

#include #include #include #include #include using namespace std; class Test { int a_; public: Test(int a):a_(a){} int get() const {return a_;} virtual bool operator <(const Test& b) const {return (*this).get() < b.get();} virtual bool operator >(const Test& b) const {return !operator <(b) ;} }; int main(int , char *[]) { list a; /*Test b(20); Test c(10); Test d(5);*/ Test* b

apple7533572009-10-26 01:52:13

#include #include #include #include using namespace std; class Test { int a_; public: Test(int a):a_(a){} int get() const {return a_;} virtual bool operator <(const Test& b) const {return (*this).get() < b.get();} virtual bool operator >(const Test& b) const {return !operator <(b) ;} }; int main(int , char *[]) { list a; Test b(20); Test c(10); Test d(5); a.push_back(&c); a.push_b

apple7533572009-10-26 01:51:03

可以使用less 或者 greater, 但是你必须在object中重载 operater <(const object*)