I came up with the following:
template <typename T> inline void printcontainer( std::vector<T> container )
{
for( auto it = container.begin(); it != container.end(); it++ )
{
std::cout << *it << std::endl;
}
}
int _tmain(int argc, _TCHAR* argv[])
{
std::vector<int> v;
v.push_back(5);
v.push_back(4);
v.push_back(3);
printcontainer(v);
return 0;
}
(Sorry for the push_backs
, visual studio doesn't accept initializer lists...ugh!!)
now this function is limited to std::vector
, how can I make it so that I can pass other containers, like std::list
arrays etc...
Simply don't template on the type stored by the container, but on the type of the container itself:
template <typename Container>
inline void printcontainer(const Container &container)
Note that I changed the argument to const
reference to avoid an unnecessary copy.
You can generalize your print function to C arrays by using the non-member std::begin
and std::end
or by using a range based for
loop:
template <typename Container>
inline void printcontainer(const Container &container) {
for (const auto &v : container)
std::cout << v << "\n";
}
OT remark: You probably do not need the inline
here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With