如何对用户定义类型的 CArray 进行排序? [英] How do I sort a CArray of a user defined type?

查看:9
本文介绍了如何对用户定义类型的 CArray 进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 C++ 中是否有内置的方法来对 CArray 进行排序?

Is there a built-in way to sort a CArray in C++?

推荐答案

std::sort() 应该可以工作:

CArray<int> arrayOfInts;
arrayOfInts.Add(7);
arrayOfInts.Add(114);
arrayOfInts.Add(3);
std::sort(arrayOfInts.GetData(), arrayOfInts.GetData()+arrayOfInts.GetSize());

这使用指向数组中第一个元素的指针作为开始迭代器,并将指向最后一个元素的指针作为最后一个迭代器(无论如何都不应该取消引用,所以一切都很好).如果数组包含更多有趣的数据,您还可以传入自定义谓词:

This uses the pointer to the first element in the array as the start iterator, and the pointer to one past the last element as the last iterator (should never be dereferenced anyway, so all's well). You could also pass in a custom predicate if the array contained more interesting data:

struct Foo
{
  int val;
  double priority;
};

bool FooPred(const Foo& first, const Foo& second)
{
   if ( first.val < second.val )
      return true;
   if ( first.val > second.val )
      return false;
   return first.priority < second.priority;
}

//... 

   CArray<Foo> bar;
   std::sort(bar.GetData(), bar.GetData()+bar.GetSize(), FooPred);

哦 - 不要使用 CArray.

这篇关于如何对用户定义类型的 CArray 进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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