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

use*_*774 2 c++ sorting templates selection template-argument-deduction

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

/*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());
}
Run Code Online (Sandbox Code Playgroud)

Tem*_*Rex 7

你有一个未受影响的模板参数T,所以你需要1)移动你typename T的第一个模板参数:

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

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);
        }
}
Run Code Online (Sandbox Code Playgroud)

调用std::min_element等同于你的for循环,iter_swap它等于你自己的swap.使用STL算法的优点是它们更可能是正确的(手写代码中的逐个错误非常常见)

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