在下面的代码中,我试图搜索一个字符串数组,我传递给特定字符串的模板函数,但是我得到错误“没有匹配的函数调用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;
}
模板与不安全的C风格的数组?来吧... – leftaroundabout 2013-04-21 18:53:40
@leftaroundabout你能多说一点吗? – user2302335 2013-04-21 19:13:30
我的意思是,为什么不使用适当的C++容器,如'std :: array'或'std :: vector',而不是'T []'? – leftaroundabout 2013-04-21 19:36:40