sort_vector.cpp 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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 <algorithm>
  11. #include <iostream>
  12. #include <vector>
  13. #include <boost/compute/system.hpp>
  14. #include <boost/compute/algorithm/copy.hpp>
  15. #include <boost/compute/algorithm/sort.hpp>
  16. #include <boost/compute/container/vector.hpp>
  17. namespace compute = boost::compute;
  18. int rand_int()
  19. {
  20. return rand() % 100;
  21. }
  22. // this example demonstrates how to sort a vector of ints on the GPU
  23. int main()
  24. {
  25. // create vector of random values on the host
  26. std::vector<int> host_vector(10);
  27. std::generate(host_vector.begin(), host_vector.end(), rand_int);
  28. // print out input vector
  29. std::cout << "input: [ ";
  30. for(size_t i = 0; i < host_vector.size(); i++){
  31. std::cout << host_vector[i];
  32. if(i != host_vector.size() - 1){
  33. std::cout << ", ";
  34. }
  35. }
  36. std::cout << " ]" << std::endl;
  37. // transfer the values to the device
  38. compute::vector<int> device_vector = host_vector;
  39. // sort the values on the device
  40. compute::sort(device_vector.begin(), device_vector.end());
  41. // transfer the values back to the host
  42. compute::copy(device_vector.begin(),
  43. device_vector.end(),
  44. host_vector.begin());
  45. // print out the sorted vector
  46. std::cout << "output: [ ";
  47. for(size_t i = 0; i < host_vector.size(); i++){
  48. std::cout << host_vector[i];
  49. if(i != host_vector.size() - 1){
  50. std::cout << ", ";
  51. }
  52. }
  53. std::cout << " ]" << std::endl;
  54. return 0;
  55. }