没有匹配的函数调用选择排序功能与模板(C ++) [英] no matching function call for selection sort function with templates(C++)

查看:149
本文介绍了没有匹配的函数调用选择排序功能与模板(C ++)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm playing around with templates and I was wondering why I'm getting a no matching function error using templates.

/*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 第一模板参数:

You have an undeduced template parameter T, so you need 1) move your typename T as the first template parameter:

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

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

and 2) to qualify your call to sort as selection_sort<int>(v.begin(), v.end());

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

BTW, here's a somwhat more generic implementation of selection sort, note it takes only an iterator and comparison function as template parameters, with the comparison function taking the value type that the iterator points to (this is C++11 code because of the default function template parameter, for C++98 compilers you need to have 2 overloads, with or without the comparison function)

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算法的优点是它们更有可能是正确的(手写代码中的一个一个错误是非常常见的)。

The call to std::min_element is equivalent to your for loop, and the iter_swap is equal to your own swap. The advantage of using STL algorithms is that they are much more likely to be correct (off-by-one errors in handwritten code are very common)

PS:使用 std :: upper_bound std :: rotate 练习给读者)

PS: you can similarly write an insertion_sort algorithm in 2 lines using std::upper_bound and std::rotate (exercise for the reader)

这篇关于没有匹配的函数调用选择排序功能与模板(C ++)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆