fork download
  1. #include <iostream>
  2. #include <vector>
  3. #include <algorithm>
  4.  
  5. class SquarePushBackIterator: public std::iterator<std::output_iterator_tag,int>
  6. {
  7. std::vector<int>& dst;
  8. public:
  9. SquarePushBackIterator(std::vector<int>& dst) : dst(dst) {}
  10. // These just return references to the iterator.
  11. // The only operation that matters is assignment.
  12. SquarePushBackIterator& operator*() { return *this; }
  13. SquarePushBackIterator& operator++() { return *this; }
  14. SquarePushBackIterator& operator++(int) { return *this; }
  15.  
  16. // The assignment squares and inserts into the destination.
  17. void operator=(int val)
  18. {
  19. dst.push_back(val * val);
  20. }
  21. };
  22.  
  23. void mergeSortedArray(std::vector<int>& data)
  24. {
  25.  
  26. // Find the iterator range for the positive values.
  27. using iter = std::vector<int>::const_iterator;
  28. iter endPositive = std::end(data);
  29. iter loopPositive = std::find_if(std::begin(data), std::end(data),
  30. [](int val) {return val >= 0; });
  31.  
  32. // Find the iterator range for the negative values.
  33. using reve = std::reverse_iterator<iter>;
  34. reve endNegative = reve(std::begin(data));
  35. reve loopNegative = reve(loopPositive);
  36.  
  37. // Create an array to put the results into.
  38. std::vector<int> result;
  39. result.reserve(data.size());
  40.  
  41. // Perform a standard merge
  42. std::merge(loopPositive, endPositive, loopNegative, endNegative,
  43. SquarePushBackIterator(result),
  44. [](int val1, int val2){return std::abs(val1) < std::abs(val2); });
  45.  
  46. // Use move assignment to put the result in the output vector.
  47. // Alternatively we could return an array by value.
  48. data = std::move(result);
  49. }
  50.  
  51. int main()
  52. {
  53. std::vector<int> arr={ -3, -2, 0, 4, 5, 8 };
  54.  
  55. mergeSortedArray(arr);
  56.  
  57. for (const auto& i : arr)
  58. {
  59. std::cout << i << ' ';
  60. }
  61. }
Success #stdin #stdout 0s 3432KB
stdin
Standard input is empty
stdout
0 4 9 16 25 64