我试图避免不得不两次使用“几乎”相同的代码。我有以下模板函数,该函数在中搜索提供的值QVector
,并将索引返回到元素。
template<class tVec,class tVal>
int upperBoundIndex(const QVector<tVec> &vec,int first,int last,tVal value)
{
//code here
}
例如,搜索以下类型的向量可以很好地工作:QVector<int>
,但是我也希望能够搜索类型的向量QVector<int*>
,因此我编写了另一个模板函数。
template<class tVec,class tVal>
int upperBoundIndex(const QVector<tVec*> &vec,int first,int last,tVal value)
{
//similar code here, but the dereferencing
}
这也可以正常工作,但是我一直想知道,有没有一种方法可以对两个函数使用相同的代码?因为我几乎将代码从一个函数复制并粘贴到另一个函数,并且到目前为止,每当我在一个函数I中进行更改时,就跳到另一个函数并应用相同的更改,是否有更好的解决方案?
ps我不是在寻找替代搜索功能,我知道例如在std名称空间中就有搜索功能。我想知道是否有一种方法可以优化我的方法。
您可以对容器Qvector进行模板化,并使其更通用,例如:
template<class Container>
int upperBoundIndex(const Container &vec,int first,int last,typename Container::value_type value)
{
// your code
}
但是我认为您应该std::upper_bound
在甚至有示例的地方使用索引来获取索引。
所以我会改用这种可重用的函数:
template<class ForwardIt, class T>
T upperBoundIndex(ForwardIt first, ForwardIt last, const T& value)
{
return (std::upper_bound (first, last, value) - first);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句