Reputation:
I want to have a function that takes in a template
for a std::vector
and prints whatever is in the vector provided it is a datatype allowed in std::cout
. I believe this needs to be recursive since what about a vector of vector of a vector.... For example, given a 1d vector
,
template< typename T>
void PrintVector(T vec)
{
for (unsigned int i = 0; i < vec.size(); i++){
std::cout << vec[i] << std::endl;
}
}
There are a few problems I have here with this code.
1. This doesn't work if it is a multi-dimensional vector, I need it to (I guess at this statement: vec[i]
) recursively go and print out that vector and do the same if there is another vector.
2. I also want it to take in a reference to the vector within the template so I don't copy a 3d vector that's like 1gb in size to print it, rather just reference so I don't allocate any memory to do so.
Any help would be appreciated!
Upvotes: 0
Views: 178
Reputation: 75697
First let's clarify some things: std::vector
is a template, but std::vector<T>
is a class (generated from the template, but that is irrelevant). Also the T
in the std::vector<T>
is a type not a template.
I also want it to take in a reference to the vector within the template
It doesn't work like that. You simply make the function parameter a reference.
Coming back to your main question. One common way to do this is with an overloaded function:
template <class T>
void print(const T& obj)
{
std::cout << obj;
}
template <class T>
void print(const std::vector<T>& v)
{
for (const auto& elem : v)
{
print(elem);
std::cout << std::endl;
}
}
When you call print
with std::vector<std::vector<int>>
the 2nd overload is chosen because it matches and is more specialized than the 1st. T
is deduced to be std::vector<int>
; print(elem)
calls 2nd overload with T
deduced as int
and here print(elem)
calls the 1st overload.
Upvotes: 1