I am trying to write a function printV() that takes some number of vectors (probably less than six) of any built-in type printable with cout, passed as const reference and prints them side by side, so that compareV(v1, v2, v3) would produce the output:
v1[1], v2[1], v3[1]
v1[2], v2[2], v3[3]
v1[3], v2[3], v3[3]
Here is the function I'm using to print a single vector:
template <typename T>
void printV(const std::vector<T> &vec)
{
for (int i = 0; i < vec.size(); i++)
{
std::cout << i << ": " << vec[i] << std::endl;
}
}
I would like to adapt this function to print multiple vectors, side by side. However, I don't know if it's possible to do something like:
template <typename... T>
void printV(const std::vector<T>... &vec)
{
//code that expands (vec...) into vec1, vec2, vec3 etc. the part I'm unsure about
for(int i = 0; i < vec1.size(); i++)// the size of the first vector will be the same as the other two
{
std::cout << i << ": " << vec1.at(i) << ", " << vec2.at(i) << ", " << vec3.at(i) << std::endl;
}
}
I would have to use some sort of utility function and an intermediate string variable to get around the fact that the pramaters cannot be accessed together in the same scope. This microsoft documentation article, as well as section 3.4.4 of "The C++ Programming Language" Recommend using recursion to seperate the first argument from all of those after it and making an overload of the function for the case with no parameters:
// From Section 3.4.4 of "The C++ Programming Language"
template<typename T, typename ... Tail>
void f(T head, Tail... tail)
{
g(head); // do something to head
f(tail...); // try again with tail
}
void f() { } // do nothing
which would prevent access to multiple parameters in a single scope. How might I get around this? Any suggestions or general advice is greatly appreciated, Thanks!
You can do this:
template <typename firstT, typename... T>
void printV(const std::vector<firstT>& first, const std::vector<T>& ... vec)
{
for(int i = 0; i < first.size(); i++)
{
std::cout << i << ": " << first.at(i);
( (std::cout << ' ' << vec.at(i)), ... );
std::cout << std::endl;
}
}