【问题标题】:C++ template using pointer and non pointer arguments in a QVector在 QVector 中使用指针和非指针参数的 C++ 模板
【发布时间】:2015-06-08 13:02:27
【问题描述】:

我试图避免使用“几乎”相同的代码两次。我有以下模板函数,它在 QVector 中搜索提供的值并返回元素的索引。

template<class tVec,class tVal>
int upperBoundIndex(const QVector<tVec> &vec,int first,int last,tVal value)
{
//code here
}

搜索例如以下类型的向量可以正常工作:QVector&lt;int&gt;,但是我也希望能够搜索该类型的向量 QVector&lt;int*&gt;,于是我又写了一个模板函数。

template<class tVec,class tVal>
int upperBoundIndex(const QVector<tVec*> &vec,int first,int last,tVal value)
{
//similar code here, but the dereferencing
}

这也很好用,但我一直在想,有没有办法可以为这两个函数使用相同的代码?因为我几乎将代码从一个函数复制并粘贴到另一个函数,到目前为止,每当我在一个函数中更改某些内容时,我都会直接跳到另一个函数并应用相同的更改,是否有更优化的解决方案?

附言我不是在寻找替代搜索功能,我知道例如在 std 命名空间中有搜索功能。我想知道是否有办法优化我的方法。

【问题讨论】:

    标签: c++ qt templates pointers


    【解决方案1】:

    您可以将容器 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

    【讨论】:

    • 感谢您的意见,我也没有考虑使用迭代器。另一个问题,std::upper_bound(...) 函数是否使用某种二进制搜索来优化性能?因为那是我在我的函数中实现的。
    • 如果您查看cplusplus.com/reference/algorithm/upper_bound 上的等效行为代码,您可以说它确实是一些二进制搜索。如果在底部滚动,复杂性与 std::binary_search 相同。通常,更倾向于使用 STL 函数,因为它们已经过优化!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多