Sunday, 15 August 2010

c++ - Is there a way to write this code in recursive form? -



c++ - Is there a way to write this code in recursive form? -

this function checks if elements of vector in vector b or not. should in contiguous form.

bool i_vec(const vector<int>& a, const vector<int>& b) { for(vector<int>::size_type = 0; <= b.size() - a.size(); i++) { if(equal(a.begin(), a.end(), &b[i])) { homecoming true; } } homecoming false; }

my recursive way. correct?

vector<int>::iterator pos; pos = search(b.begin(),b.end(),a.begin(),a.end()); if (pos != b.end()) { cout << "true" << endl; homecoming true; } cout << "false" << endl; homecoming false; }

just any iterative algorithm can converted recursive one, question should asking is: idea?

for, example, function add together unsigned numbers:

def add(a,b): homecoming + b

can made recursive with:

def add(a,b): if == 0: homecoming b homecoming add(a-1,b+1)

however, that's horrible thought , you're run out of stack space pretty expression:

c = add(9999999999,4)

for specific case when have 2 sorted vectors, can quite similar thing, finding first mutual element using recursion advance each list index concurrently. like, 1 time you've found mutual element:

def contains(a,idxa,b,idxb): if idxa >= a.size or idxb >= b.size: homecoming true if a[idxa] != b[idxb]: homecoming false homecoming contains(a,idxa+1,b,idxb+1)

but have same problem add above. big plenty list, you'll exhaust stack space before result.

the "better" way check to, resursive solution, find first mutual element, then advance indexes concurrently in loop. both more readable , less prone restrictions imposed recursion.

c++ loops vector

No comments:

Post a Comment