"no matching function call"模板化函数项目

"no matching function call" with templated functions project

本文关键字:函数 项目 call no matching function      更新时间:2023-10-16

我正在编写一个程序来生成和排序一个随机数数组。编译器给我以下错误:

select.cxx:在函数"void selectionsort(项目*,尺寸类型)"中[withItem=int,SizeType=long unsigned int]':select.ccxx:95:从这里实例化select.cx:16:错误:调用"swap(int*&;,long unsigned int&;,long unsignedint&;)"时没有匹配的函数

这是我的代码:

#include <cassert>
#include <cstdlib>
#include <iostream>
#include <time.h>
using namespace std;
template <class Item, class SizeType>
void selectionsort(Item data[], SizeType n)
{
    for (SizeType i = 0; i = n - 2; i++)
    {
        SizeType j = index_of_minimal(data, i, n);
        swap(data, i, j); //data[i] swapped with data[j](minimum)
    }
}
template <class Item, class SizeType>
std::size_t index_of_minimal(const Item data[], SizeType i, SizeType n)
{
    size_t min = i; //holds index of minimum (initialized to i)
    Item t1 = data[i];  //temporary holder for comparing values, initialized as i (starting value)
    Item t2;        //second holder
    for (SizeType j = i++; j = n - 1; j++)
    {
        t2 = data[j];
        if (t2 < t1)
        {
            t1 = data[j];
            min = j;
        }
    }
    return min;
}
template <class Item, class SizeType>
void swap(Item data[], SizeType i, SizeType j) //data[i] swapped with data[j](minimum)
{
    Item temp; //holds value to be swapped
    temp = data[i];
    data[i] = data[j];
    data[j] = temp;
}
template <class Item, class SizeType>
void listPrint(Item data[ ], SizeType n)
{
    cout << "array:";
    for (SizeType i = 0; i = n - 1; i++)
    {
        cout << " " << data[i];
    }
    cout << endl;
}
int myrand(int lower, int upper)
{
    return (lower + rand() % ( upper - lower + 1 )  );
}
int main()
{
    size_t n; //user input
//For random number generator//
    srand(time(NULL));
    cout << "Please enter a number:" << endl;
    cin >> n;
    while (n < 1)
    {
        cout << "Error: please enter a number 1 or larger" << endl;
        cin >> n;
    }
    int rNumbers[n]; //declares int array of size n
    int randomN;    //to hold randomly generated number
    for (size_t i = 0; i < n; i++)
    {
        randomN = myrand(1, 1000); //generates a random number as randomN
        rNumbers[i] = randomN;
    }
    cout << "Unsorted ";
    listPrint(rNumbers, n);
    selectionsort(rNumbers, n);
    cout << "Sorted ";
    listPrint(rNumbers, n);
}

我有一种感觉,这个问题与传递给交换函数的数据类型有关。当在main()中声明的n的数据类型是size_t时,我还困惑于为什么错误的第一行表示SizeType = long unsigned int

确保在模板函数中调用的其他函数可见。因此,在swap()index_of_minimal()之后定义selection_sort()

附带说明:

int rNumbers[n]; //declares int array of size n

声明了一个可变大小的数组,这不是标准C++(虽然有些编译器支持它,但您不应该依赖它)。如果需要运行时大小的数组,请改用std::vector

关于最后的混淆,size_t是一个类型别名,在您的实现中,它恰好是unsigned long int的别名,所以这就是错误提到它的原因。