对元素的向量或指向元素的指针进行排序
Sort vector of elements or pointers to elements
是否可以编写一个可以对vector<MyType>
或vector<MyType*>
进行排序的函数?
我有现有的代码
template <class Iterator>
void SortMyType(Iterator first, Iterator last) {
std::sort(first, last, [](const MyType& a, const MyType& b) {
return a.some_value() < b.some_value();
});
}
当我有std::vector<MyType>
时效果很好.但是现在我想对std::vector<MyType*>
进行排序,我想使用完全相同的逻辑。有可能做这样的事情吗?
如果你抽象出"获取值"部分,你可以重用该函数的大部分。
template <class Iterator>
void SortMyType(Iterator first, Iterator last) {
using ObjeceType = decltype(*first);
std::sort(first, last, [](const ObjectType& a, const ObjectType& b) {
return getValue(a) < getValue(b);
});
}
哪里
ReturnType getValue(MyType const& o)
{
return o.some_value;
}
ReturnType getValue(MyType const* p)
{
return getValue(*p);
}
相关文章:
- 查找两个排序向量中共有的元素
- C++ 如何比较n个排序的整数向量以找到互元素?
- 如何在 c++ 中根据第二个元素按降序对列表进行排序
- 对的排序向量 (std::vector<pair<int, int>>) 按对的第一个元素搜索并更新第二个元素值
- 高级选择排序 - 在一次迭代中搜索两个元素
- 为什么用户定义的函数不按照给定的顺序对相同长度的元素进行排序?
- 为什么这个选择排序算法仍然切换一个元素,当它已经是其他元素中最小的元素时?
- 快速排序 - 三个中位数枢轴选择 - 某些元素顺序不正确
- 将一系列已排序的元素划分为相邻组
- 如何通过保持第一个插入的位置来对列表中插入的其余元素进行排序?
- 保持排序的数据结构,允许log N插入时间,并且可以返回我在log N中查找的元素的索引
- "x"的所有元素都存在于"y"(排序向量)中吗?
- 如何根据对的第二个元素对 STL c++ 中的一组对进行排序?
- 如何在保持它们连接到同一元素的同时对 2 个数组进行排序?
- 使用 pair 创建priority_queue,以便在第一个元素相等时"<"第一个元素的排序,对第二个元素">"排序
- 如何将元素排序到矩阵C++
- 如何保持按第二个元素排序的对的优先级队列?
- 如何从两个数组中生成一对向量,然后使用CUDA/Thrust按对的第一个元素排序
- 部分排序数组,最后n个元素排序
- 如何对一对向量按降序排序,并按第二个元素排序