c++ - 在 c++ 中使用自定义仿函数对数组进行排序,其中母类是通用的

标签 c++ list sorting functor

所以我想使用对象仿函数对子类中母类中的数组进行排序。母类是通用的。

template<typename T>
class MotherClass
{
public:
  /* some code */

  std::list<T*> getList();

private:
  std::list<T*> list_;
}

子类使用另一个类作为模板

class OtherClass
{
public:
  /* some code */

  std::string getName() const;

private:
  std::string name_;
}

这是仿函数类

class Functor
{
public:
  /* some code */

  bool operator() (OtherClass* a, OtherClass* b) const
  {
    return a->getName() < b->getName();
  }
}

最后是子类

class ChildClass : public MotherClass<OtherClass>
{
public:
  /* some code */

  friend std::ostream& operator<<(std::ostream& o, const ChildClass& child);
}

std::ostream& operator<<(std::ostream& o, const ChildClass& child)
{
  Functor functor;
  std::sort(child.getList().begin(), child.getList().end(), functor);

  /* some code */
}

当我评论 ChildClass 中的排序行时,解决方案构建没有任何问题。但是,当它存在时,会发生此错误。

error C2784: 'unknown-type std::operator -(std::move_iterator<_RanIt> &,const std::move_iterator<_RanIt2> &)': could not deduce template argument for 'std::move_iterator<_RanIt> &' from 'std::_List_unchecked_iterator>>'

有人可以帮忙吗?

最佳答案

std::sort 所述 documentation它需要随机访问迭代器,std::list 没有提供。这就是为什么 std::list 有自己的方法 std::list::sort所以解决方案可能是:

Functor functor;
auto list = child.getList();
list.sort( functor );

注意:即使您使用支持随机访问迭代器的容器,您的方法也不会起作用,每次调用 child.getList() 都会创建一个新拷贝,所以您会得到 UB在 2 个不同的实例上调用 begin()end()。如果您的想法是对数据成员进行排序,则需要通过引用返回它,这不是一个好主意,但在技术上可行:

// if getList() returns reference this would work
Functor functor;
child.getList().sort( functor );

但最好将仿函数传递给 MotherClass 的方法,这样会对其进行排序 数据。

关于c++ - 在 c++ 中使用自定义仿函数对数组进行排序,其中母类是通用的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40725885/

相关文章:

java - 如何对对象的 ArrayList 进行排序?

c++ - 在 C++ 中排序 vector

c++ - 显式模板特化和从属名称查找问题

c++ - 如何删除 vector 中的最后一个和/或唯一元素?

c++ - 自动为 Qt 配置套件

python - 如何在 Python 中构建一个所有值都是 [] 的独立实例的字典?

ios - 如何在nsmutabledictionary ios中按顺序打印键

java - 如何检查Windows版本是否是正版?

python - 查找二维数组元素的第一个和第二个元素之间的最大和最小差异

C# List - 在循环/迭代时删除项目