vector_addition.cpp 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. //---------------------------------------------------------------------------//
  2. // Copyright (c) 2013 Kyle Lutz <kyle.r.lutz@gmail.com>
  3. //
  4. // Distributed under the Boost Software License, Version 1.0
  5. // See accompanying file LICENSE_1_0.txt or copy at
  6. // http://www.boost.org/LICENSE_1_0.txt
  7. //
  8. // See http://boostorg.github.com/compute for more information.
  9. //---------------------------------------------------------------------------//
  10. #include <iostream>
  11. #include <boost/compute/algorithm/copy.hpp>
  12. #include <boost/compute/algorithm/transform.hpp>
  13. #include <boost/compute/container/vector.hpp>
  14. #include <boost/compute/functional/operator.hpp>
  15. namespace compute = boost::compute;
  16. // this example demonstrates how to use Boost.Compute's STL
  17. // implementation to add two vectors on the GPU
  18. int main()
  19. {
  20. // setup input arrays
  21. float a[] = { 1, 2, 3, 4 };
  22. float b[] = { 5, 6, 7, 8 };
  23. // make space for the output
  24. float c[] = { 0, 0, 0, 0 };
  25. // create vectors and transfer data for the input arrays 'a' and 'b'
  26. compute::vector<float> vector_a(a, a + 4);
  27. compute::vector<float> vector_b(b, b + 4);
  28. // create vector for the output array
  29. compute::vector<float> vector_c(4);
  30. // add the vectors together
  31. compute::transform(
  32. vector_a.begin(),
  33. vector_a.end(),
  34. vector_b.begin(),
  35. vector_c.begin(),
  36. compute::plus<float>()
  37. );
  38. // transfer results back to the host array 'c'
  39. compute::copy(vector_c.begin(), vector_c.end(), c);
  40. // print out results in 'c'
  41. std::cout << "c: [" << c[0] << ", "
  42. << c[1] << ", "
  43. << c[2] << ", "
  44. << c[3] << "]" << std::endl;
  45. return 0;
  46. }