如何格式化推力::复制(ostream_iterator).

How to format thrust::copy(ostream_iterator)

本文关键字:ostream iterator 复制 格式化      更新时间:2023-10-16

摘要

我正在使用此示例打印设备矢量。我想让阵列排列。

格式设置仅应用于第一个数字。

我的代码

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 to 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 调用自定义打印f

//----------------------------
//      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;
}