说我希望23到57之间的所有数字都在vector
。我可以这样做:
vector<int> result;
for (int i = 23; i <= 57; ++i)
{
result.push_back(i);
}
但这是一个简单的工作的5线解决方案。我不能更优雅地做到这一点吗?例如,最好的语法是vector<int> result{23 .. 57};
或者这样一个简单的一行代码。 C ++ 17的任何选项?
答案 0 :(得分:16)
您可以使用std::iota
(自C ++ 11起)。
从
value
开始并重复评估++value
,按顺序增加值填充[first,last]范围。该函数以编程语言APL中的整数函数named命名。
e.g。
std::vector<int> result(57 - 23 + 1);
std::iota(result.begin(), result.end(), 23);
答案 1 :(得分:3)
使用range-v3,它将是:
const std::vector<int> result = ranges::view::ints(23, 58); // upper bound is exclusive
答案 2 :(得分:1)
另一种可能性是使用boost::counting_iterator
[1]。这也有使用C ++ 98的优点,如果你不幸被卡住了。
#include <boost/iterator/counting_iterator.hpp>
...
result.insert(result.end(), boost::counting_iterator<int>(23), boost::counting_iterator<int>(58));
或者,甚至更简单:
vector<int> result(boost::counting_iterator<int>(23), boost::counting_iterator<int>(58));
请注意,在任何一种情况下都需要正常的半开放范围,您必须使用lastNum+1
,否则您将无法插入numeric_limits<int>::max()
(又名INT_MAX
因为这个原因。
[1] https://www.boost.org/doc/libs/1_67_0/libs/iterator/doc/counting_iterator.html