在 QVector 中使用指针和非指针参数的 C++ 模板

标签 c++ qt templates pointers

我试图避免两次使用“几乎”相同的代码。我有以下模板函数,它在 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);
}

Live example

关于在 QVector 中使用指针和非指针参数的 C++ 模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30709868/

相关文章:

c++ - 更改 ItemData 的内容

c++ - QAbstractProxyModel 不更新 dataChanged() 信号

c++ - 相当于 %02d 与 std::stringstream?

python - sphinx - 如何更改文档样式表

javascript - 当 tr 必须存在于模板中时,使用 Marionette ItemView 生成无语义的表标记

wordpress - 无法从标题中删除 Feed 链接

c++ - 帮我解决 "template parameters not used in partial specialization"

c++ - 使用 C++ 的巴贝奇数未显示正确的结果

c++ - 从Finder打开文件时如何获取文件路径

c++ - 类构造函数 "C2248: ' std::basic_ios<_Elem,_Traits>::basic_ios':无法访问类 'std::basic_ios<_Elem,_Traits>"中声明的私有(private)成员