1. 程式人生 > >編寫一個遞迴模板函式,確定元素x是否屬於陣列a[0:n-1]

編寫一個遞迴模板函式,確定元素x是否屬於陣列a[0:n-1]

利用pos記錄遞迴的層數,當遞迴到第n + 1層(也就是到了判斷x == a[n]時)返回false

C++程式碼如下:

#include <bits/stdc++.h> // 萬能標頭檔案(注意:POJ上無法使用)
using namespace std;

template<class T>
bool in_the_array(const vector<T>& a, int x, int pos) //遞迴判斷元素x是否在陣列a中,其中pos代表陣列的元素位置,pos < n時合法
{
	int n = a.size();

	if (pos >= n) return false;

	if (x == a[pos] && pos < n)
		return true;
	else
		return in_the_array(a, x, pos + 1); // 遞迴判斷元素x是否在陣列a中
}

int main()
{
	vector<int> a {1, 3, 2, 4, 3, 6, 5}; // 自定義陣列(向量)
	int x; // 待判斷元素
	while (cin >> x)
	{
		if (in_the_array<int>(a, x, 0)) // 呼叫遞迴函式
			cout << "Yes\n";
		else
			cout << "No\n";
	}
	return 0;
}