1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
|
#include <vector>
#include <iostream>
#include <type_traits>
#include <cmath>
template<typename T>
typename std::enable_if_t< std::is_arithmetic_v<T>, std::vector<T>>
range(T begin, T end, T stepsize = 1) {
std::vector<T> result {};
result.reserve(static_cast<size_t>(std::ceil((0.0 + end - begin ) / stepsize)));
if (begin < end)
for (; begin < end; result.push_back(begin), begin += stepsize);
else
for (; begin > end; result.push_back(begin), begin += stepsize);
return result;
}
int main() {
std::cout << '\n';
// range(1, 50) // (1)
auto res { range(1, 50) };
for (const auto i : res)
std::cout << i << " ";
std::cout << "\n\n";
// range(1, 50, 5) // (2)
res = range(1, 50, 5);
for (const auto i : res)
std::cout << i << " ";
std::cout << "\n\n";
// range(50, 10, -1) // (3)
res = range(50, 10, -1);
for (const auto i : res)
std::cout << i << " ";
std::cout << "\n\n";
// range(50, 10, -5) // (4)
res = range(50, 10, -5);
for (const auto i : res)
std::cout << i << " ";
std::cout << "\n\n";
}
| |