将
std::vector<int>
设置为某个范围的最佳方法是什么,例如3 到 16 之间的所有数字?
如果您有 C++11 支持或正在使用 STL
,则可以使用
std::iota
:
std::vector<int> v(14);
std::iota(v.begin(), v.end(), 3);
或者如果没有的话实现你自己的。
如果您可以使用
boost
,那么一个不错的选择是 boost::irange
:
std::vector<int> v;
boost::push_back(v, boost::irange(3, 17));
std::vector<int> myVec;
for( int i = 3; i <= 16; i++ )
myVec.push_back( i );
参见例如这个问题
#include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>
template<class OutputIterator, class Size, class Assignable>
void iota_n(OutputIterator first, Size n, Assignable value)
{
std::generate_n(first, n, [&value]() {
return value++;
});
}
int main()
{
std::vector<int> v; // no default init
v.reserve(14); // allocate 14 ints
iota_n(std::back_inserter(v), 14, 3); // fill them with 3...16
std::for_each(v.begin(), v.end(), [](int const& elem) {
std::cout << elem << "\n";
});
return 0;
}
上的输出
std::iota - 很有用,但它需要迭代器,在创建向量之前,......所以我采取自己的解决方案。
#include <iostream>
#include <vector>
template<int ... > struct seq{ typedef seq type;};
template< typename I, typename J> struct add;
template< int...I, int ...J>
struct add< seq<I...>, seq<J...> > : seq<I..., (J+sizeof...(I)) ... >{};
template< int N>
struct make_seq : add< typename make_seq<N/2>::type,
typename make_seq<N-N/2>::type > {};
template<> struct make_seq<0>{ typedef seq<> type; };
template<> struct make_seq<1>{ typedef seq<0> type; };
template<int start, int step , int ... I>
std::initializer_list<int> range_impl(seq<I... > )
{
return { (start + I*step) ...};
}
template<int start, int finish, int step = 1>
std::initializer_list<int> range()
{
return range_impl<start, step>(typename make_seq< 1+ (finish - start )/step >::type {} );
}
int main()
{
std::vector<int> vrange { range<3, 16>( )} ;
for(auto x : vrange)std::cout << x << ' ';
}
Output:
3 4 5 6 7 8 9 10 11 12 13 14 15 16
尝试使用
std::generate
。它可以根据公式生成容器的值
std::vector<int> v(size);
std::generate(v.begin(),v.end(),[n=0]()mutable{return n++;});
ranges::iota
。
#include <vector>
#include <numeric>
int main() {
int start = 3, end = 16;
std::vector<int> v(end - start + 1); // initialize with 14 zeros
std::ranges::iota(v, start); // fill with consecutive integers starting from 3
// v={3,4,5,...,3+14-1}
}
或者,要从空
vector
开始添加元素,可以将 ranges::generate_n
(自 C++ 20 起)与 back_inserter
结合使用。
以下示例也可以轻松修改以使用与 1 不同的步骤。
#include <vector>
#include <algorithm>
#include <iterator>
#include <iostream> // only used for output in this example
int main() {
int start = 3, end = 16;
int len = end - start + 1;
std::vector<int> v;
v.reserve(len); // allocate enough space for elements
std::ranges::generate_n(std::back_inserter(v), len,
[i=start]() mutable {return i++;});
std::ranges::copy(v, std::ostream_iterator<int>(std::cout, " ")); // output
}