C ++如何排序向量< class *>其中, [英] C++ how to sort vector<class *> with operator <

查看:137
本文介绍了C ++如何排序向量< class *>其中,的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有

  class c1 {

public:
int number;

c1()
{
number = rand()%10;
}

bool operator< (c1 * w)
{
return number< w-> number;
}


};

vector< c1 *> vec = {...}
sort(vec.begin(),vec.end())

为什么要排序?



但如果我们有

  bool operator< (c1 w)
{
return number<数字
}

  vector< c1> vec = {...} 

它会被排序!

解决方案

最直接的方法是定义一个函数

  bool c1_ptr_less(c1 const * lhs,c1 const * rhs){
return lhs-> something< rhs-> something;
}

std :: sort(vec.begin(),vec.end(),& c1_ptr_less);

我建议的是一个通用函数来处理全部指针数组

  struct pointer_less {
template<类型名T>
bool operator()(T const * lhs,T const * rhs)const
{return * lhs< * rhs; }
};

std :: sort(vec.begin(),vec.end(),pointer_less());使用这个,定义通常的 c1 :: operator<



< (const c1&)
,同样对于其他类。



一般来说,最好的做法是完全避免指针,包括指针数组。 / p>

i have

 class c1{

public:
    int number;

    c1()
    {
        number=rand()%10;
    }

    bool operator < (c1 *w)
    {
        return number < w->number;
    }


};

vector<c1*> vec = { ... }
sort(vec.begin(),vec.end()) 

why it dosent sort ?

but if we had

 bool operator < (c1 w)
    {
        return number < w.number;
    }

and

vector<c1> vec = { ... }

it would have been sorted !

解决方案

The most straightforward approach is to define a function

bool c1_ptr_less( c1 const *lhs, c1 const *rhs ) {
    return lhs->something < rhs->something;
}

std::sort( vec.begin(), vec.end(), & c1_ptr_less );

What I would suggest is a generic functor to take care of all pointer arrays

struct pointer_less {
    template< typename T >
    bool operator()( T const *lhs, T const *rhs ) const
        { return * lhs < * rhs; }
};

std::sort( vec.begin(), vec.end(), pointer_less() );

Armed with this, define the usual c1::operator< ( const c1 & ) and likewise for other classes.

Generally, best practice is to avoid pointers entirely, including arrays of pointers.

这篇关于C ++如何排序向量&lt; class *&gt;其中,的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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