在下面的代碼中,我試圖搜索一個字符串數組,我傳遞給特定字符串的模板函數,但是我得到錯誤「沒有匹配的函數調用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