没有匹配函数调用选择排序函数与模板(c++)

no matching function call for selection sort function with templates(C++)

本文关键字:c++ 函数 排序 函数调用 选择      更新时间:2023-10-16

我正在玩模板,我想知道为什么我得到一个不匹配的函数错误使用模板。

/*selection sort*/
template <typename InputIterator, typename T>
void selection_sort(InputIterator first, InputIterator last){
    InputIterator min;
    for(; first != last - 1; ++first){
        min = first;
        for(T i = (first + 1); i != last ; ++i)
        {
            if(*first < *min)
                min = i;
        }
        myswap(*first, *min);
    }
}
int main(){
    int a[] = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1};
    vector<int> v(a, a+10);
    selection_sort(v.begin(),v.end());
}

您有一个未推导的模板参数T,因此您需要1)移动您的typename T作为第一个模板参数:

// now InputIterator will be deduced
template <typename T, typename InputIterator>
void selection_sort(InputIterator first, InputIterator last)
{
    // your implementation
}

和2)将您的排序调用限定为selection_sort<int>(v.begin(), v.end());

顺便说一句,这里有一个更通用的选择排序实现,注意它只接受一个迭代器和比较函数作为模板参数,比较函数接受迭代器指向的值类型(这是c++ 11代码,因为默认函数模板参数,对于c++ 98编译器你需要有2个重载,带或不带比较函数)

template< typename ForwardIterator, typename Compare = std::less<typename std::iterator_traits<ForwardIterator>::value_type> >
void selection_sort(ForwardIterator first, ForwardIterator last, Compare cmp = Compare())
{
        for (auto it = first; it != last; ++it) {
                auto const selection = std::min_element(it, last, cmp);
                std::iter_swap(selection, it);
        }
}

std::min_element的调用相当于你的for循环,而iter_swap等于你自己的交换。使用STL算法的优点是它们更有可能是正确的(手写代码中差1的错误非常常见)

PS:您可以类似地使用std::upper_boundstd::rotate(读者练习)在2行中编写insertion_sort算法

问题是typename T似乎不被使用,不能由编译器推断。您必须显式地指定类型:

selection_sort<vector<int>::iterator, int>(v.begin(),v.end());