我试图避免两次使用“几乎”相同的代码。我有以下模板函数,它在 QVector
中搜索提供的值并返回元素的索引。
template<class tVec,class tVal>
int upperBoundIndex(const QVector<tVec> &vec,int first,int last,tVal value)
{
//code here
}
例如,搜索以下类型的 vector 效果很好:QVector<int>
,但是我也希望能够搜索该类型的 vector
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
}
这也能正常工作,但我一直在想,有没有一种方法可以对这两个函数使用相同的代码?因为我几乎是将代码从一个函数复制并粘贴到另一个函数,所以到目前为止,每当我在一个函数中更改某些内容时,我都会直接跳到另一个函数并应用相同的更改,是否有更优化的解决方案?
附注我不是在寻找替代搜索功能,我知道例如在 std 命名空间中有搜索功能。我想知道是否有办法优化我的方法。
最佳答案
您可以模板化您的容器 Qvector 并使其更通用,例如:
template<class Container>
int upperBoundIndex(const Container &vec,int first,int last,typename Container::value_type value)
{
// your code
}
但我认为你应该使用 std::upper_bound
甚至有一个 example to get the index .
所以我会改用这种可重用的函数:
template<class ForwardIt, class T>
T upperBoundIndex(ForwardIt first, ForwardIt last, const T& value)
{
return (std::upper_bound (first, last, value) - first);
}
关于在 QVector 中使用指针和非指针参数的 C++ 模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30709868/