Wednesday, July 9, 2014

Print vector recursively

Someone asked a question on Stack Overflow about printing the contents of a vector recursively. The OP provided no code and the question was downvoted and eventually deleted. Here's a quick and dirty way to do it using iterators.

Tested with Visual Studio 2012.

#include <iostream>
#include <vector>

template <class Iterator>
void print (Iterator iter, Iterator end)
{
    if (iter == end) {
        return ;
    }

    std::cout << *iter << "\n" ;

    print (++iter, end) ;
}

int main (void)
{
    int vals [] = {5, 10, 15, 20} ;
    std::vector <int> v (vals, vals + 4) ;

    print (v.cbegin (), v.cend ()) ;

    return 0 ;
}

No comments:

Post a Comment