Write a function in C++ named “SortByAbsoluteValue” in the folder named “Sorting” that…
- User
Write a function in C++ named “SortByAbsoluteValue” in the folder named “Sorting” that takes a reference to a std::istream and a reference to an std::ostream. From the istream, it should read in a series of ints separated by spaces. The function should write these ints to the ostream separated by a single space (with a trailing space character). I’ve included code that does this already. However, the order of these ints should be from smallest to largest by absolute value. Meaning that the sign of the int doesn’t affect its order in the stream, only the absolute value. You can assume that no two ints have the same absolute value. Example Input Stream: 0 43 -5 67 11 -40 Example Output String: 0 -5 11 -40 43 67
- Assistant
#include <iostream> #include <vector> #include <algorithm> #include <cmath> using namespace std; void SortByAbsoluteValue(std::istream& is, std::ostream& os) { vector<int> nums; int x; while (is >> x) { nums.push_back(x); } sort(nums.begin(), nums.end(), [](int a, int b){ return abs(a) < abs(b); }); for (auto num : nums) { os << num << " "; } os << endl; } int main() { SortByAbsoluteValue(cin, cout); return 0; } - User
Write a templated function, named “LongestPositiveRun” in LongestPositiveRun/header.hpp that takes a vector of numbers and returns a vector of numbers. The vector returned should be the longest consecutive run of positive numbers in the input vector. I’ve already written code that returns the longest run of numbers that starts from the beginning of the vector, you are welcome to modify this to solve the inputs where the longest run starts on an element other than the first. input = {7, 0, 1, 3, 6, 2, -5, 6, 2, -8}; expected = {1, 3, 6, 2}; result = LongestPositiveRun(input); CHECK(result == expected); // {1, 3, 6, 2} is the longest run of positive values {7}, and {6, 2} are both shorter. Note: your solution should work on vectors of ints, doubles, longs and so forth.
- Assistant
Here is the implementation of the templated function "LongestPositiveRun":
#ifndef LONGESTPOSITIVERUN_HEADER_HPP #define LONGESTPOSITIVERUN_HEADER_HPP #include <vector> #include <type_traits> template <typename T, typename = typename std::enable_if<std::is_arithmetic<T>::value, T>::type> std::vector<T> LongestPositiveRun(const std::vector<T>& nums) { std::vector<T> result; std::vector<T> current; for (auto num : nums) { if (num > 0) { current.push_back(num); } else { if (current.size() > result.size()) { result = current; } current.clear(); } } if (current.size() > result.size()) { result = current; } return result; } #endif // LONGESTPOSITIVERUN_HEADER_HPP