【发布时间】:2012-08-11 12:54:01
【问题描述】:
将std::vector<int> 设置为范围的最佳方法是什么,例如3 到 16 之间的所有数字?
【问题讨论】:
-
这可能会有所帮助:stackoverflow.com/a/7256008/8331
标签: c++ c++11 stl stdvector iota
将std::vector<int> 设置为范围的最佳方法是什么,例如3 到 16 之间的所有数字?
【问题讨论】:
标签: c++ c++11 stl stdvector iota
如果您支持 C++11 或正在使用 the 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));
【讨论】:
v.reserve(14) 将保存默认初始化。
std::back_inserter则不会
iota 什么时候停止?没有办法告诉它“在 N 个数字后停止”。
iota_n 答案来进行预先内存预留,而不是默认初始化 0...0 然后立即用 3...16 覆盖.如果 N = 140 亿而不是 14 会怎样?
std::vector<int> myVec;
for( int i = 3; i <= 16; i++ )
myVec.push_back( i );
【讨论】:
myVec.reserve(14) 会更好。
参见例如这个question
#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;
}
Ideone 上的输出
【讨论】:
back_inserter 会调用push_back,但如果你插入大量元素,push_back 会依次进行大量的重新分配。
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
【讨论】:
range<3, 16>() 比使用std::iota 更好。
尝试使用std::generate。它可以根据公式为容器生成值
std::vector<int> v(size);
std::generate(v.begin(),v.end(),[n=0]()mutable{return n++;});
【讨论】: