我正在尝试编写一个基于模板的函数频率,该频率将返回项目数组中的项目出现的计数。
到目前为止我有
#include <iostream>
using namespace std;
template <class T>
T frequency(T array[], T arraySize, T item) {
int count = 0;
for (int i = 0; i < arraySize; i++) {
if (array[i] == item) {
count++;
}
}
return count;
}
int main() {
// Testing template with int
int intArray[10] = { 1, 2, 3, 3, 14, 3, 2, 7, 99, 2 };
cout << "{ ";
for (int i = 0; i < 10; i++) {
cout << intArray[i] << " ";
}
cout << "}" << endl;
cout << "Frequency of 3: " << frequency(intArray, 10, 3) << endl;
cout << "Frequency of 2: " << frequency(intArray, 10, 2) << endl;
cout << "Frequency of 99: " << frequency(intArray, 10, 99) << endl;
// Testing template with double
double doubleArray[10] = { 1.5, 2.2, 99.4, 132.11, 1.5, 2.22, 1.515, 66.2, 51.8, 34.0 };
cout << "{ ";
for (int j = 0; j < 10; j++) {
cout << doubleArray[j] << " ";
}
cout << "}" << endl;
cout << "Frequency of 1.5: " << frequency(doubleArray, 10, 1.5) << endl;
cout << "Frequency of 2.2: " << frequency(doubleArray, 10, 2.2) << endl;
cout << "Frequency of 100.1: " << frequency(doubleArray, 10, 100.1) << endl;
return 0;
}
但是,当我尝试打印出双打的频率时,我会遇到"无匹配函数的匹配函数(double [10],int,double)'"。我不确定我做错了什么。
感谢您的任何帮助!
frequency
使用相同类型的数组和 arraySize
的元素参数,即 T
。但是,您通过不同类型的参数,即double
与int
。然后类型扣除失败,因为无法推导T
(确定)。
根据您的启动,arraySize
类型似乎是固定的,您可以将其声明为std::size_t
或int
。返回类型也是如此。他们的类型不会改变,然后不应使用模板参数声明。
template <class T>
int frequency(T array[], std::size_t arraySize, T item) {
int count = 0;
for (std::size_t i = 0; i < arraySize; i++) {
if (array[i] == item) {
count++;
}
}
return count;
}
您不应将模板参数与arraysize一起使用。因为您将其与i
,int i = 0; i < arraySize;
进行了比较。返回类型也不应该是T,因为双重不准确,请勿像计数器那样使用它。另外,您进行return count
,然后写int count = 0;
template <class T>
int frequency(T const array[], int arraySize, T const &item);
请注意,标准库为此目的具有模板函数。在生产代码中,您应该使用std::count_if()
。
int count = std::count_if(intArray.begin(), intArray.end(), [](int i){ return i == 42; });
您可以将频率误以为,因此可以与其他容器一起使用。
#include <iostream>
#include <vector>
using namespace std;
template <class outputIterator,class T>
int frequency(outputIterator b,outputIterator e ,const T& v) {
int count = 0;
while(b != e)
{
if(*b == v)
{
count++;
}
b++;
}
return count;
}
int main ()
{
std::vector<int> first={1,1,2,3,4,5,5};
std::cout<<frequency(first.begin(),first.end(),1)<<std::endl;
int arr[]={1,2,3,5,5,5};
std::cout<<frequency(std::begin(arr),std::end(arr),5)<<std::endl;
return 0;
}