題目:
編寫一個模板函數 inner_product,返回值是∑a[i]*b[i] (i 從 0到 n - 1)。測試你的代碼。
思路:
由題可知,本函數計算的是兩個數組的內積。內積一般是數字,如整數,浮點數。函數返回值應該設置為與數組元素相同類型。
代碼:
1 #include <iostream> 2 using namespace std; 3 4 template <typename T> 5 T inner_product(const T* a, const T* b, int array_size) { 6 T result = 0; 7 for (int i = 0; i < array_size; ++i) { 8 result += (a[i] * b[i]); 9 } 10 11 return result; 12 } 13 14 int main() { 15 int a[5] { 0, 1, 2, 3, 4 }; 16 int b[5] { 5, 4, 3, 2, 1 }; 17 int result = inner_product(a, b, 5); 18 cout << "Inner product : " << result << endl; 19 20 return 0; 21 }
代碼中有幾處需要說明:
第一,將形參聲明為 const T*,因為函數不應該修改數組元素。
第二,函數內局部變量 result 初始化為 0,因為數組元素為數字,可以這樣初始化。
