如何格式化推力::: copy(ostream_iterator)

时间:2019-08-09 14:56:28

标签: c++ cuda thrust

摘要

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

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

我的代码

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  

格式设置仅应用于第一个数字。如果我更改宽度或填充,则将其应用于第一个数字,而不应用于其余数字。

注意

  • 我仅使用了“ _”字符,因此可以看到格式在哪里应用。

  • 输出位于代码块中,因为否则,堆栈溢出将覆盖我的格式并删除顺序空格。

1 个答案:

答案 0 :(得分:0)

我找不到将推力::: 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;
    }

编辑

我发现了另一个可行的选择。 Example

使用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;
    }