sort() 在向量指针中的变式

当使用sort函数对指针容器排序时,单纯使用sort(begin, end)无法得到预期结果。根据MSDN,需要提供第三个参数Pred pr,这是一个自定义比较算子,尤其适用于处理包含私有成员的情况。通过定义友元函数或提供接口来实现该算子,可以成功实现指针的正确排序。若尝试直接重载小于运算符为指针类型,同样无法达到预期效果,因此必须使用自定义比较算子。" 102468408,8706296,Python实时摄像头人脸检测,"['Python编程', '计算机视觉', '人脸识别', '图像处理']
摘要由CSDN通过智能技术生成

 

​
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;

class Cc
{
public:
   Cc(const Cc& c)
   {
      m_str=c.m_str;
   }
   Cc(string str)
   {
      m_str=str;
   }

   const string get() const
   {
      return m_str;
   }

   void show() const
   {
      cout<<m_str;
   }

   const Cc operator+(const string& str)
   {
      return Cc(m_str+str);
   }
   bool operator<(const Cc& c)
   {
      return m_str<c.m_str;
   }


private:
   string  m_str;

};

int main()
{
   Cc a("1");
   Cc b("4");
   Cc c("3");
   Cc d("2");
   vector<Cc*> vec1;
   vec1.push_back(&a);
   vec1.push_back(&b);
   vec1.push_back(&c);
   vec1.push_back(&d);
   vector<Cc*>::iterator itb=vec1.begin(),ite=vec1.end();
   for(int i=0;i<4;i++)
   {
      vec1[i]->show();
   }
   sort(itb, ite);
   for(int i=0;i<4;i++)
   {
      vec1[i]->show();
   }

    return 0;
}

​

如果用sort(begin ,end )的话得不到想要结果, 查询MSDN知道sort有第三参数(Pred pr )算子,用来对于指针类型的容器进行修正;

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;

class Cc
{
public:
   Cc(const Cc& c)
   {
      m_str=c.m_str;
   }
   Cc(string str)
   {
      m_str=str;
   }

   const string get() const
   {
      return m_str;
   }

   void show() const
   {
      cout<<m_str;
   }

   const Cc operator+(const string& str)
   {
      return Cc(m_str+str);
   }
   bool operator<(const Cc& c)
   {
      return m_str<c.m_str;
   }


private:
   string  m_str;

};

bool Great(const Cc*a, const Cc*b)
{
   return a->get()<b->get();
}

int main()
{
   Cc a("1");
   Cc b("4");
   Cc c("3");
   Cc d("2");
   vector<Cc*> vec1;
   vec1.push_back(&a);
   vec1.push_back(&b);
   vec1.push_back(&c);
   vec1.push_back(&d);
   vector<Cc*>::iterator itb=vec1.begin(),ite=vec1.end();
   for(int i=0;i<4;i++)
   {
      vec1[i]->show();
   }
   sort(itb, ite,Great);
   for(int i=0;i<4;i++)
   {
      vec1[i]->show();
   }

    return 0;
}

算子需要用到私有成员, 要么给接口,要么定义友元函数,不赘述。

这样就可以得到想要的结果了

(如果我改原来的函数小于的重载改成指针会有什么情况)

也同样得不到结果, 所以一定要给一个算子

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值