c++ - 如何使用此 C++ 模板函数。简单的初学者问题

标签 c++

我找到了这个合并排序函数,但我不知道如何使用它。 请帮忙

#include<iostream>
#include<stdlib.h>
#include<vector>
using namespace std;

template <typename Comparable>
void mergeSort(vector<Comparable*> &v)
{
    mergeSortPart(v, 0, v.size() - 1);
}

template <typename Comparable>
void mergeSortPart(vector<Comparable*> &v,int first,int last)
{  
    if(first < last)
    {
        int mid = (first + last)/2;
        mergeSortPart(v, first, mid);
        mergeSortPart(v, mid + 1, last);
        merge(v, first, mid, last);
    }
}
template <typename Comparable>
void merge(vector<Comparable*> &v, int first, int mid,int last)
{
    vector<Comparable*> temp(v.size());
    int first1 = first; int last1 = mid; int first2 = mid + 1;
    int last2 = last; int index = first1;
    while((first1 <= last1) && (first2 <= last2))
    {
        if(*v[first1]<*v[first2])
            temp[index++] = v[first1++];
        else
            temp[index++] = v[first2++];
    }
    while(first1 <= last1)
        temp[index++] = v[first1++];
    while(first2 <= last2)
        temp[index++] = v[first2++];
    for(index = first; index <= last; index++)
        v[index] = temp[index];
}

void main()
{  
    vector<int> arr (20);
    for(int i=0;i<20;i++)
        arr[i]=i;
    mergeSort<int>(arr);
}

main函数我试图声明一个包含 6 个元素的数组并调用 mergeSort模板函数,但它给出了一个编译错误:

Error 1 error C2664: 'mergeSort' : cannot convert parameter 1 from 'std::vector<_Ty>' to 'std::vector<_Ty,_Ax> &'

我对模板函数不是很熟悉,所以如果有人能告诉我如何使用这个函数,那对我来说是一种享受

谢谢

最佳答案

作为 mergeSort 的参数是vector<Comparable*> ,它只能对指针 vector 进行排序,而不能对整数或其他对象的 vector 进行排序。

关于c++ - 如何使用此 C++ 模板函数。简单的初学者问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5926194/

相关文章:

c++ - 是否可以从指针的多态容器返回 'accurate' 对象?

c++ - CMake 生成的 Xcode 项目不显示头文件

c++ - atof() 返回 float 而不是 double

c++ - 如何使用 Telnet 库从服务器发送查询并从客户端接收回显

c++ - read() 缓冲区有无效数据(指针问题?)

c++ - 管理 2 个 Internet 连接?

c++ - 使用操纵器忽略标点符号

c++ - 使用 Cmake 和 Visual Studio 2013 Unresolved external 问题

c++ - `std::transform` 的 vector 加法赋值

c++ - 可以通过 const 说明符重载函数吗?