简体   繁体   English

VexCL:vexcl向量中的最大值的索引

[英]VexCL: Index of maximum value in a vexcl vector

How can I find the index of the maximum value in a VexCL vector? 如何在VexCL向量中找到最大值的索引? I can find the maximum value: 我可以找到最大值:

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);

Which gives m = 5 but is there a way to find the index of the maximum value, ind = 3 ? 给出m = 5但是有没有办法找到最大值的索引ind = 3

You will need to 您将需要

  1. encode both vector value and vector position in a vexcl expression, and 在vexcl表达式中对向量值和向量位置进行编码,并且
  2. create custom functor for vex::Reductor that would reduce the above expression based on its first component. 为vex :: Reducor创建自定义函子,该函子将基于其第一个成分来简化上述表达式。

Here is the working code: 这是工作代码:

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

This outputs 这个输出

max value of 5 at position 3

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM