C++ 将 std::vector<int> 设置为一个范围
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11965732/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Set std::vector<int> to a range
提问by Andreas
What's the best way for setting an std::vector<int>
to a range, e.g. all numbers between 3 and 16?
将 an 设置std::vector<int>
为一个范围的最佳方法是什么,例如 3 到 16 之间的所有数字?
回答by juanchopanza
You could use std::iota
if you have C++11 support or are using the STL:
你可以使用std::iota
,如果你有C ++ 11的支持或正在使用的STL:
std::vector<int> v(14);
std::iota(v.begin(), v.end(), 3);
or implement your own if not.
或者如果没有,请实施您自己的。
If you can use boost
, then a nice option is boost::irange
:
如果您可以使用boost
,那么一个不错的选择是boost::irange
:
std::vector<int> v;
boost::push_back(v, boost::irange(3, 17));
回答by SingerOfTheFall
std::vector<int> myVec;
for( int i = 3; i <= 16; i++ )
myVec.push_back( i );
回答by TemplateRex
See e.g. this 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;
}
Output on Ideone
回答by Khurshid Normuradov
std::iota - is useful, but it requires iterator, before creation vector, .... so I take own solution.
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
回答by Tianrong Wang
Try to use std::generate
. It can generate values for a container based on a formula
尝试使用std::generate
. 它可以根据公式为容器生成值
std::vector<int> v(size);
std::generate(v.begin(),v.end(),[n=0]()mutable{return n++;});