Your 'recursion end' condition is "off-by-one" – it should be if (s1 > 1)
instead of if (s1 > 0)
.
As it stands, you end up calling cElemet
with a value of 0
(froms1 - 1
) and then, in that recursion, you attempt to access ar1[s1 - 1]
when s1
is zero, which causes undefined behaviour.
Changing your function to the following fixes the problem – for your sample arrays (even when I tested by jumbling up the data values). However, there may be issues for arrays of size 1
.
template <class T>
vector<T> cElemet(T ar1[], int s1, T ar2[], int s2)
{
vector<T> v;
if (s1 > 1) // Don't call recursively when s1 is 1 ...
v = cElemet(ar1, s1 - 1, ar2, s2);
if (contains(ar2, s2, ar1[s1 - 1])) { // ... or we have UB here.
cout << "+" << ar1[s1 - 1];
v.push_back(ar1[s1 - 1]);
}
return v;
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…