c++ - 如果可能的话,我如何使用可变参数模板来制作一个并排打印多个任何类型的 std::vectors 的函数?
问题描述
我正在尝试编写一个函数 printV(),它需要一些可使用 cout 打印的内置类型的向量(可能少于六个),作为 const 引用传递并并排打印,以便 compareV(v1, v2 , v3) 将产生输出:
v1[1], v2[1], v3[1]
v1[2], v2[2], v3[3]
v1[3], v2[3], v3[3]
这是我用来打印单个向量的函数:
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;
}
}
我想调整这个函数来并排打印多个向量。但是,我不知道是否可以执行以下操作:
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;
}
}
我将不得不使用某种实用函数和一个中间字符串变量来解决无法在同一范围内一起访问 pramaters 的事实。 这篇 microsoft 文档文章以及“C++ 编程语言”的第 3.4.4 节建议使用递归将第一个参数与其后面的所有参数分开,并为没有参数的情况重载函数:
// 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
这将阻止访问单个范围内的多个参数。我该如何解决这个问题?非常感谢任何建议或一般建议,谢谢!
解决方案
你可以这样做:
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;
}
}
推荐阅读
- html - 未应用样式表
- javascript - 是否可以在没有内联函数的情况下从 reduce 和 curry 创建 sum 函数?
- vue.js - db 错误,axios get 方法返回(TypeError:int() 参数必须是字符串、类似字节的对象或数字,而不是 'AnonymousUser')500
- swift - 从 firebase 检索数据失败
- flask - 如何通过将 mimetype 添加到 Flask 中的 json 数据类型来修复 make_response 错误
- perl - 尝试在 SFTP 中实现双重身份验证
- java - Servlet 在应该重定向时给出一个空白页面
- django - 如何在 Django rest 框架中为多个类创建序列化器?
- c# - C# + 从存储过程中读取输出结果 + 合并到 + OUTPUT
- keras - 无法在加载的模型上使用 predict_generator