jua*_*nza 53
std::iota如果你有C++ 11支持或正在使用STL,你可以使用:
std::vector<int> v(14);
std::iota(v.begin(), v.end(), 3);
Run Code Online (Sandbox Code Playgroud)
或者如果没有实施自己的.
如果你可以使用boost,那么一个不错的选择是boost::irange:
std::vector<int> v;
boost::push_back(v, boost::irange(3, 17));
Run Code Online (Sandbox Code Playgroud)
Sin*_*all 19
std::vector<int> myVec;
for( int i = 3; i <= 16; i++ )
myVec.push_back( i );
Run Code Online (Sandbox Code Playgroud)
参见例如这个问题
#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;
}
Run Code Online (Sandbox Code Playgroud)
Ideone上的输出