Search code examples
c++stringrecursionstdlist

How to use recursion in std::list?


I am having trouble executing this block of code. The first base condition of this code(for searching a string in a list of strings) does not work. Thanks.

int string_check(list<string> l,list<string>::iterator it,string s)
{   
if(it==l.end()) return 0;
if(*it==s) return 1;
return(string_check(l,++it,s));
}

Solution

  • You're passing the list by value, so l.end() is the end of a different list each time, and never the one that it came from.

    Either pass the list by reference; or pass the end iterator rather than the list itself. That would be a more flexible solution, allowing you to decouple the function from a specific container type and support any range of input iterators:

    template <typename InIter, typename T>
    bool contains(InIter begin, InIter end, T const & value) {
        if (begin == end) return false;
        if (*begin == value) return true;
        return contains(++begin, end, value);
    }
    

    Recursion is often a bad idea, as the stack is typically fairly small and causes horrible bugs if it overflows. Unless this is an exercise in implementing such a function, use iteration:

    for (; begin != end; ++begin) {
        if (*begin == value) return true;
    }
    return false;
    

    or the standard library:

    return std::find(begin, end, value) != end;