zoukankan      html  css  js  c++  java
  • 【转】vector中对象指针的排序

    原文:http://blog.csdn.net/tanlijun37/article/details/1948493

    vector中对象指针的排序,初步想法是
    1: 把对象指针存到vector,重载bool operator(对象指针)
    2:用sort来排序
    例:
    class A
    {
    public:
      bool operator(const A* temp)
      {
         return this->a < temp->a;
      }
      A(int a)
      {
        this->a = a;
      }
      int a;
    };
    vector<A*> vec;
    vec.push_back(new A(10));
    vec.push_back(new A(5));
    vec.push_back(new A(4));
    sort(vec.begin(), vec.end);

    然而排序的结果却不对
    后来上网查了一下,原来当我排序vector的时候,它比较的是指针,而不是对象,并且operator<重载符的参数应该用引用,而不是指针

    解决办法:
    1:声明一个全局的比较函数
    例:
    bool CompLess(const A* lhs, const A* rhs)
    {
        return lhs->GetA() < rhs->GetA();
    }
    sort(vec.begin(), vec.end, CompLess);
    2: 声明一个函数对象
    class CompLess2
    {
    public:
        bool operator()(const A* lhs, const A* rhs)
        {
            return lhs->GetA() < rhs->GetA();
        }
    };
    sort(vec.begin(), vec.end, CompLess2);

  • 相关阅读:
    Win10 UWP程序内的文件格式
    第一章
    英语
    BOM
    html基础
    协程
    python
    列表 元组 range
    我的Python学习笔记(四):动态添加属性和方法
    我的Python学习笔记(三):私有变量
  • 原文地址:https://www.cnblogs.com/wubugui/p/4307180.html
Copyright © 2011-2022 走看看