将字符串数组传递给模板化搜索函数
Passing a string array to templated search function
在下面的代码中,我试图搜索一个字符串数组,我传递给一个特定字符串的模板函数,但我得到错误"没有匹配的函数调用' arraySearch"。前两个函数调用int数组和double数组工作得很好,似乎我只是错过了处理字符串数组的细节,我不能弄清楚它是什么。无论如何,它必须是一个数组(不能是向量)。任何帮助将非常感激!
#include<iostream>
#include<string>
using namespace std;
template<typename T>
bool arraySearch(T array[], int size, T thing)
{
for(int i = 0; i < size; i++)
{
if(array[i] == thing)
return true;
}
return false;
}
int main()
{
const int SIZE = 12;
int intArray[] = {14, 3, 6, 76, 34, 22, 21, 54, 33, 23, 76, 234};
cout << "The element was found: " << arraySearch(intArray, SIZE, 23) << endl;
double doubleArray[] = {34.5, 65.56, 11.1, 45.4, 87.5, 98.3, 23.6, 15.5, 3.3, 5.44, 54.3, 99.9};
cout << "The element was found: " << arraySearch(doubleArray, SIZE, 23.6) << endl;
string stringArray[] = {"cool", "bug", "master", "katze", "republic", "randolph", "watermelon", "igloo", "sardine", "cream", "yellow", "rubber"};
cout << "The element was found: " << arraySearch(stringArray, SIZE, "cool") << endl;
system("pause");
return 0;
}
你需要说:
cout << "The element was found: " << arraySearch(stringArray, SIZE, std::string("cool")) << endl;
问题是"cool"
不是T
的实例,当模板被T
实例化为std::string
时。在c++中,字符串字面值是C字符数组,而不是std::string
。
同样,您可以简单地使用<algorithm>
中的std::find
来达到与您发布的代码相同的效果。std::find
可以使用C数组和指针,也可以使用c++迭代器。
std::string* res = std::find(stringArray, stringArray + sizeof(stringArray) / sizeof(std::string), "cool");
问题是T
从第一个参数推断为std::string
,从第二个参数推断为const char*
。
因此,编译器不知道选择哪一个。试着做:
arraySearch(stringArray, SIZE, std::string("cool"))
或者,让函数模板接受不同类型的实参:
template<typename T, typename U>
bool arraySearch(T array[], int size, U thing)
不需要显式地构造一个std::string
对象:
arraySearch(stringArray, SIZE, "cool")
如果您决定采用这种方式,您可能需要进一步sfinae约束您的函数模板,以便它只接受相等可比的类型:
template<typename T, typename U,
decltype(declval<T>() == declval<U>())* = nullptr>
bool arraySearch(T array[], int size, U thing)
相关文章:
- 如何在动态数组上使用搜索函数
- 为什么二叉搜索函数会抛出错误?
- 这是在传递 int num 时创建搜索函数的正确方法吗?使用链表库
- 如何将Z3_ast导出为二进制以及如何搜索函数名称?
- 替代搜索函数和哈希向量<struct>C++
- 返回 std::p air<const CustomClass &, bool> 用于搜索函数中的失败情况,当 CustomClass 是抽象基类时
- 我如何使用此二叉搜索函数的修改后的最大/最小值创建新数组
- 有没有办法在 UBUNTU 中的大型库文件夹(.a 和 .so 文件)中搜索函数
- BST搜索函数在一台机器上返回true,在另一台机器中返回false
- 使用cctype库搜索函数,以查找某个范围内的数字字符数
- 在元组中搜索函数的参数
- C++有序链表搜索函数算法逻辑
- 二叉搜索树 - 搜索函数返回对象 (C++)
- 关于修复对向量的线性搜索函数的调用的建议
- 搜索函数返回相同的,而不考虑二叉搜索树中存在的项目
- C++中的二进制搜索函数返回无限循环
- 具有两个字符串向量的搜索函数
- 使用哈希表中的派生类搜索函数
- C++二进制搜索函数
- 为什么我的应用程序在错误的DLL中搜索函数