How do I sort a CArray of a user defined type?(如何对用户定义类型的 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 进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何对用户定义类型的 CArray 进行排序?
基础教程推荐
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 这个宏可以转换成函数吗? 2022-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 常量变量在标题中不起作用 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
