【问题标题】:In C++, is it possible to easily sort a vector of object type pointers, with respect to any attribute of those objects?在 C++ 中,是否可以针对这些对象的任何属性轻松地对对象类型指针的向量进行排序?
【发布时间】:2011-03-11 15:04:37
【问题描述】:

是否可以根据这些对象的任何属性轻松地对对象类型指针向量进行排序?

假设students是对象类型指针的向量,当对象studentStudent的类型并且有两个方法student.studentAlias()student.studentName()。如何根据别名对向量进行排序?

提前致谢。

【问题讨论】:

标签: c++ sorting attributes vector


【解决方案1】:

你可以使用仿函数:

#include <vector>
#include <algorithm>

class StudentAliasComparator
{
public:
    bool operator()(const Student* left, const Student* right) const
    {
        return left->studentAlias() < right->studentAlias();
    }
};

void SortVectorOfStudentByAlias(std::vector<Student*>& students)
{
    std::sort(students.begin(), students.end(), StudentAliasComparator());
}

您也可以从 boost 或语言中使用 lambda(如果您使用 C++0x)。使用 C++0x 语法,它会类似于(无法检查,因为我现在无法访问支持 C++0x 的 C++ 编译器):

void SortVectorOfStudentByAlias(std::vector<Student*>& students)
{
    std::sort(students.begin(), students.end(),
        [](const Student* l, const Student* r) {
            return l->studentAlias() < r->studentAlias(); })
}

【讨论】:

    【解决方案2】:

    您可以使用 std::sort 算法进行排序:

    template <class RandomAccessIterator, class StrictWeakOrdering>
    void sort(RandomAccessIterator first, RandomAccessIterator last, StrictWeakOrdering comp);
    

    只需提供一个对您感兴趣的属性执行小于比较的函数对象 (comp)。

    【讨论】:

      【解决方案3】:

      使用std::mem_fun 和一个包装器:

      #include <algorithm>
      #include <functional>
      
      template <typename F>
      struct CompareBy
      {
          bool operator()(const typename F::argument_type& x,
                          const typename F::argument_type& y)
          { return f(x) < f(y); }
      
          CompareBy(const F& f) : f(f) {}
      
       private:
          F f;
      };
      
      template <typename F>
      CompareBy<F> by(const F& f) { return CompareBy<F>(f); }
      

      排序,做

      std::vector<Student*> students;
      
      std::sort(students.begin(), students.end(), 
                by(std::mem_fun(&Student::studentAlias))
      );
      

      如果要按成员变量排序,很遗憾没有std::mem_ptr。使用我的回答 there 中的想法来构建你自己的。

      【讨论】:

      • 非常感谢您的帮助。
      猜你喜欢
      • 2017-09-14
      • 2020-09-17
      • 2014-03-11
      • 2014-12-29
      • 2023-02-09
      • 2021-09-20
      • 2010-12-20
      • 2011-07-07
      • 2011-10-01
      相关资源
      最近更新 更多