2024-04-29 06:20:29 发布
网友
std::vector
# Python >>> x = range(0, 10) >>> x [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
我想我可以使用std::generate_n并提供一个函子来生成序列,但是我想知道是否有一种更简洁的方法来使用STL?
std::generate_n
有boost::irange:
std::vector<int> x; boost::push_back(x, boost::irange(0, 10));
#include <vector> #include <numeric> //std::iota std::vector<int> x(10); std::iota(std::begin(x), std::end(x), 0); //0 is the starting number
我最后写了一些实用函数来完成这个任务。您可以按如下方式使用它们:
auto x = range(10); // [0, ..., 9] auto y = range(2, 20); // [2, ..., 19] auto z = range(10, 2, -2); // [10, 8, 6, 4]
代码:
#include <vector> #include <stdexcept> template <typename IntType> std::vector<IntType> range(IntType start, IntType stop, IntType step) { if (step == IntType(0)) { throw std::invalid_argument("step for range must be non-zero"); } std::vector<IntType> result; IntType i = start; while ((step > 0) ? (i < stop) : (i > stop)) { result.push_back(i); i += step; } return result; } template <typename IntType> std::vector<IntType> range(IntType start, IntType stop) { return range(start, stop, IntType(1)); } template <typename IntType> std::vector<IntType> range(IntType stop) { return range(IntType(0), stop, IntType(1)); }
有boost::irange:
我最后写了一些实用函数来完成这个任务。您可以按如下方式使用它们:
代码:
相关问题 更多 >
编程相关推荐