如何格式化推力::复制(ostream_iterator).
How to format thrust::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 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;
}
相关文章:
- ostream过载时的缓冲区冲洗
- 需要从 istream 和 ostream 派生 iostream
- "ostream &os"有什么用?
- 为什么常量词在重载运算符中不与 ostream 对象一起使用<<?
- 在调试模式下引发C++ "deque iterator not dereferencable"异常
- std::iterator::reference 必须是引用吗?
- 我的运算符重载是否有效<<(流插入)左操作数不是 ostream
- C++表达SFINAE和ostream操纵器
- 在抛出 'std::runtime_error' 的实例后终止调用 what(): Filebuf 和 ostream 的 I/O 错误
- oStream 不打印添加两个 valarray 的结果(使用运算符重载)
- 逗号在重载 ostream 和 istream 在结构中分开
- 为什么unordered_set<string::iterator>不起作用?
- 为什么 Clang std::ostream 写一个 std::istream 无法读取的双精度?
- ostream 运算符<< 为获取 STL 容器而过载,传递 std::string 会破坏它?
- 将 ostream 包装在类中并模板化<<运算符
- 如何在C++中编写 ostream 的向量,它接收所有不同的输出流,如 cout、ostringstream 和 ofs
- 为什么在返回 ostream 类时使用引用?
- 将标准输出重定向到ostream
- boost::interprocess::file_lock 与 std::ostream 一起使用时的错误行为
- ostream<<Iterator, C++