是否可以编写一个可以对a vector<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();
});
}
Run Code Online (Sandbox Code Playgroud)
当我拥有时效果很好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);
});
}
Run Code Online (Sandbox Code Playgroud)
哪里
ReturnType getValue(MyType const& o)
{
return o.some_value;
}
ReturnType getValue(MyType const* p)
{
return getValue(*p);
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
55 次 |
最近记录: |