c++ - 如何格式化推力::copy(ostream_iterator)
问题描述
概括
我正在使用此示例打印设备矢量。我想让阵列排成一行。
格式设置仅应用于第一个数字。
我的代码
template <typename Iterator>
void print_range(const std::string& name, Iterator first, Iterator last)
{
typedef typename std::iterator_traits<Iterator>::value_type T;
std::cout << name << ": ";
thrust::copy(first, last, std::ostream_iterator<T>(std::cout << std::setw(4) << std::setfill(' '), " "));
std::cout << "\n";
}
重要的一行是:
thrust::copy(first, last, std::ostream_iterator < T > (std::cout << std::setw(4) << std::setfill(' '), " "));
电流输出
Box Numbers :: _110 109 108 109 108 107 106 105 106 105
Difference :: _110 -1 -1 1 -1 -1 -1 -1 1 -1
Difference 2:: _110 -111 0 2 -2 0 0 0 2 -2
Key Vector :: _110 -1 -1 1 -1 -1 -1 -1 1 -1
Inclusive :: _110 -1 -2 1 -1 -2 -3 -4 1 -1
期望的输出
Box Numbers :: _110 109 108 109 108 107 106
Difference :: _110 -1 -1 1 -1 -1 -1
Difference 2:: _110 -111 0 2 -2 0 0
Key Vector :: _110 -1 -1 1 -1 -1 -1
Inclusive :: _110 -1 -2 1 -1 -2 -3
格式设置仅应用于第一个数字。如果我更改宽度或填充,它会应用于第一个数字,但不会应用于其余数字。
笔记
我只使用了“_”字符,所以我可以看到格式的应用位置。
输出在代码块中,因为否则堆栈溢出会覆盖我的格式并删除顺序空格。
解决方案
我找不到将thrust::copy 的输出格式化为cout 的方法。最终复制到宿主载体。然后我可以遍历宿主向量并格式化输出。
不太优雅,但可以为此目的完成工作。
template <typename Iterator>
void print_range(const std::string& name, Iterator first, Iterator last)
{
// Print Vector Name
std::cout << name << ": ";
// Copy Vector to host
int print_length = thrust::distance(first, last);
thrust::host_vector<int> to_print(print_length);
thrust::copy(first, last, to_print.begin());
// Print Vector
for (auto val : to_print)
std::cout << setw(4) << val;
std::cout << endl;
}
编辑
我找到了另一个同样有效的选项。例子
使用 for_each 调用自定义 printf
//----------------------------
// Print Functor
//----------------------------
struct printf_functor
{
__host__ __device__
void operator() (int x)
{
printf("%4d ", x);
}
};
//----------------------------
// Print Range
//----------------------------
template <typename Iterator>
void print_range(const std::string& name, Iterator first, Iterator last)
{
// Print Vector Name
std::cout << name << ": ";
// Print Each Element
thrust::for_each(thrust::device, first, last, printf_functor());
std::cout << endl;
}
推荐阅读
- python - 当我尝试使用 asyncpg 连接我的 postgress sql13 时出现错误
- deep-learning - BoxClassifierLoss/localization_loss 和 Loss/regularization_loss 使用 Tensorflow Objectdetection API 也为零
- java - 有没有办法在 Java 中获取所有 MIDI 设备的列表?
- ruby-on-rails - Kubernetes 中的 Rails 没有获取 configmap 提供的环境变量
- r - 跨某些列的逐行 NA 计数 - 按 id 分组
- loops - 当有重复时,数独功能不起作用。导致无限循环
- amazon-web-services - 创建访问策略以使用 IP 地址将弹性 beantalk 连接到 Elasticsearch
- javascript - .on('click') 可以用来添加数字值吗?
- algorithm - 找到通过顶点 u 和 v 的最小权重电路
- json - Groovy 将 XML 转换为 JSON 数组