I am new to generic functions in C++. I have a template function that prints the inside of a vector.
template<class T>
void print(vector<T> v){
for(typename vector<T>::iterator it=v.begin(); it != v.end() ; it++)
cout << *it << endl;
}
I want to write a more generic print()
to print an STL container's inside. How can I proceed from this point on?
There's already a generic algorithm that can do that, using iterators for both the input and the output:
std::copy(v.begin(), v.end(), std::ostream_iterator<T>(std::cout, "\n"));
As such, I would proceed by using what's already there. If you really like the syntax of print(container_name);
(which I'll admit is attractive), you could use this as the implementation, something like this:
template <class Container>
void print(Container const &c) {
std::copy(std::begin(c), std::end(c),
std::ostream_iterator<typename Container::value_type>(std::cout, "\n"));
}
I'd note that (in C++11) it's often more convenient to use a range-based for
loop than std::copy
though:
template <class Container>
void print(Container const &c) {
for (auto const &item : c)
std::cout << item << "\n";
}
Either of these should work for most real containers, though I'd generally prefer the latter, not only because it's simpler, but also because it's a little more generic. The first requires an actual container the defines a value_type
member, so you can't apply it to a built-in array, for one example. You can remove that particular limitation by using std::iterator_traits<iterator>::value_type
if you want to badly enough, but the latter avoids the problem entirely (and simplifies the code quite a bit in the process).