2014-07-10 175 views
0

如何找到VexCL向量中最大值的索引?我能找到的最大值:VexCL:vexcl向量中最大值的索引

int h[] = {3, 2, 1, 5, 4}; 
vex::vector<int> d(ctx, 5); 
vex::copy(h, d); 

vex::Reductor<int, vex::MAX> max(ctx.queue()); 
int m = max(d); 

其中给出m = 5但有没有办法找到最大值,ind = 3的指数?

回答

2

您需要

  1. 编码在vexcl表达两个矢量值和矢量的位置,和
  2. 创建烦恼::减速器定制算符,这将减少其基于第一部件上的上述表达式。

下面是工作的代码:

#include <iostream> 
#include <vector> 
#include <vexcl/vexcl.hpp> 

// This function converts two integers to cl_int2 
VEX_FUNCTION(cl_int2, make_int2, (int, x)(int, y), 
     int2 v = {x, y}; 
     return v; 
     ); 

// This struct compares OpenCL vector types by the first component. 
struct MAX0 { 
    template <class Tn> 
    struct impl { 
     typedef typename vex::cl_scalar_of<Tn>::type T; 

     // Initial value. 
     static Tn initial() { 
      Tn v; 

      if (std::is_unsigned<T>::value) 
       v.s[0] = static_cast<T>(0); 
      else 
       v.s[0] = -std::numeric_limits<T>::max(); 

      return v; 
     } 

     // Device-side function call operator 
     struct device : vex::UserFunction<device, Tn(Tn, Tn)> { 
      static std::string name() { return "MAX_" + vex::type_name<Tn>(); } 
      static std::string body() { return "return prm1.x > prm2.x ? prm1 : prm2;"; } 
     }; 

     // Host-side function call operator 
     Tn operator()(Tn a, Tn b) const { 
      return a.s[0] > b.s[0] ? a : b; 
     } 
    }; 
}; 

int main(int argc, char *argv[]) { 
    vex::Context ctx(vex::Filter::Env); 

    std::vector<int> h = {3, 2, 1, 5, 4}; 
    vex::vector<int> d(ctx, h); 

    // Create reductor based on MAX0 operation, 
    // then reduce an expression that encodes both value and position of a 
    // vector element: 
    vex::Reductor<cl_int2, MAX0> max(ctx); 

    cl_int2 m = max(make_int2(d, vex::element_index())); 

    std::cout << "max value of " << m.s[0] << " at position " << m.s[1] << std::endl; 
} 

此输出

max value of 5 at position 3