是否可以编写一个可以对avector<MyType>
或a进行排序的函数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>
。但是现在我想对a进行排序,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);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句