首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

函数模板,该怎么处理

2012-03-17 
函数模板写一个函数模板。该函数的参数包括一个部分填充的数组和数组基类型的一个值。如果指定的值在部分填

函数模板
写一个函数模板。
该函数的参数包括一个部分填充的数组和数组基类型的一个值。如果指定的值在部分填充的数组中,那么函数返回包含那个值第一个索引变量的索引;如果指定的值不在数组中,函数返回-1。数组的基类型是一个类型参数。需要两个参数来给出部分填充的数组,一个指定数组,另一个指定使用的索引变量数量。并写一个测试程序测试。


[解决办法]
#include <iostream>

template <typename T>
int FindIndex ( const T* anArray, int arraySize, const T& value)
{
int index = -1;
for (int i=0; i <arraySize; ++i) {
if (anArray[i]==value) {
index = i;
break;
}
}

return index;
}


int main()
{
using namespace std;

int arraySize = 10;
int* dArray = new int[arraySize];
char* cArray = new char[arraySize];
for (int i=0; i <arraySize; ++i) {
dArray[i] = i;
cArray[i] = 'a '+i;
}

cout < <FindIndex(dArray, arraySize, 1) < <endl;
cout < <FindIndex(dArray, arraySize, 5) < <endl;
cout < <FindIndex(dArray, arraySize, 12) < <endl;

cout < <FindIndex(cArray, arraySize, 'a ') < <endl;
cout < <FindIndex(cArray, arraySize, 'L ') < <endl;
cout < <FindIndex(cArray, arraySize, 'b ') < <endl;

delete []dArray;
delete []cArray;

system( "pause ");

return 0;


}
[解决办法]
#include <iostream>
#include <cstddef> //for size_t
using namespace std;

template <class T, size_t n>
size_t findx(const T (&array)[n], const T &value) {
for (size_t i = 0; i < n; ++i) {
if (array[i] == value)
return i;
}
return -1;
}

int main()
{
int arr[] = {1, 2, 5, 78, -56, 128, 7, 0, 9};
size_t pos = findx(arr, 128);
if (pos != -1)
cout < < "found: " < < arr[pos] < < endl;
else
cout < < "not found: 128 " < < endl;

pos = findx(arr, 100);
if (pos != -1)
cout < < "found: " < < arr[pos] < < endl;
else
cout < < "not found: 100 " < < endl;

return 0;
}

[解决办法]
只能用于能使用 "== "比较的

#include <iostream>
using namespace std;

template <class T>
T FindValue(T* arr, int size, T value)
{
for(int i = 0; i < size; i++)
if(arr[i] == value) return i;
return -1;

}

int main()
{
int iArr[] = {1,2,3,3,4,5,6};
cout < < "pos: " < <FindValue(iArr, 7, 3) < <endl;
return 0;
}

热点排行