I'm trying to avoid having to use "nearly" the same code twice. I have the following template function, which searches for the provided value in a QVector
and returns the index to the element.
template<class tVec,class tVal>
int upperBoundIndex(const QVector<tVec> &vec,int first,int last,tVal value)
{
//code here
}
Searching for example a vector of the following type works fine: QVector<int>
, however I'd like to also be able to search a vector of the type
QVector<int*>
, so I wrote another template function.
template<class tVec,class tVal>
int upperBoundIndex(const QVector<tVec*> &vec,int first,int last,tVal value)
{
//similar code here, but the dereferencing
}
This also works fine, but I've been wondering, is there a way I can use the same code for both functions? Because I nearly copy and pasted the code from one function to the other, and so far whenever I changed something in one function I, jumped right to the other and applied the same changes, is there a more optimal solution?
p.s. I'm not looking for alternative search functions, I know there are search functions for example in the std namespace. I'd like to know if there's a way to optimize my approach.
You could template your container Qvector and make it more generic with something like :
But I think you should use
std::upper_bound
where you even have an example to get the index.So I would use this kind of reusable function instead :
Live example