在C++/STL中是否有一个与Python Rangee()相当的紧凑

2024-04-29 06:20:29 发布

您现在位置:Python中文网/ 问答频道 /正文

如何使用C++和STL来做以下的等价操作?我想用一个值范围[min,max]填充std::vector

# Python
>>> x = range(0, 10)
>>> x
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

我想我可以使用std::generate_n并提供一个函子来生成序列,但是我想知道是否有一种更简洁的方法来使用STL?


Tags: 方法range序列minmaxgeneratestdvector
3条回答

boost::irange

std::vector<int> x;
boost::push_back(x, boost::irange(0, 10));
<>在C++ 11中,有{{CD1}}:

#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));
}

相关问题 更多 >