我需要生成一个数字序列,具有一个开始,结束值和一个生成数字的步骤。例如,在Haskell语言中,这是一个小问题,被称为算术序列。
[1..10] = [1,2,3,4,5,6,7,8,9,10]
我尝试如下实现。
namespace utility {
template<class Container, class Type>
Container generator(Type t_from, Type t_to, Type t_step = 1)
{
// Sequence storage container
Container sequence_of_numbers { };
sequence_of_numbers.reserve(static_cast<std::size_t>(std::abs(t_to - t_from + 1)) / t_step);
// For floating point data
if constexpr (std::is_floating_point_v<Type>) {
// The reverse sequence
if((t_to - t_from) < 0) {
for(Type i = t_from; ; i -= t_step) {
if(i > t_to) {
sequence_of_numbers.push_back(static_cast<typename Container::value_type>(i));
} else {
if(std::fabs(i - t_to) < std::numeric_limits<Type>::epsilon()) {
sequence_of_numbers.push_back(i);
}
break;
}
}
// The direct sequence
} else {
for(Type i = t_from; ; i += t_step) {
if(i < t_to) {
sequence_of_numbers.push_back(static_cast<typename Container::value_type>(i));
} else {
if(std::fabs(i - t_to) < std::numeric_limits<Type>::epsilon()) {
sequence_of_numbers.push_back(i);
}
break;
}
}
}
// Integer data type
} else {
if((t_to - t_from) < 0) {
for(Type i = t_from; i >= t_to; i -= t_step) {
sequence_of_numbers.push_back(static_cast<typename Container::value_type>(i));
}
} else {
for(Type i = t_from; i <= t_to; i += t_step) {
sequence_of_numbers.push_back(static_cast<typename Container::value_type>(i));
}
}
}
sequence_of_numbers.shrink_to_fit();
return sequence_of_numbers;
}
}
下一个电话我得到了想要的结果。
std::vector<int> full_reverse_sequence { utility::generator<std::vector<int>>(10000, 0) };
在语法或STL库级别的C ++ 17 / C ++ 20中是否有类似的东西?