将std :: vector <int>设置为范围</int>

时间:2012-08-15 07:49:53

标签: c++ c++11 stl stdvector iota

std::vector<int>设置为范围的最佳方式是什么,例如3到16之间的所有数字?

5 个答案:

答案 0 :(得分:48)

如果您有C ++ 11支持或正在使用std::iota,则可以使用the STL

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));

答案 1 :(得分:19)

std::vector<int> myVec;
for( int i = 3; i <= 16; i++ )
    myVec.push_back( i );

答案 2 :(得分:8)

参见例如这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

上的输出

答案 3 :(得分:1)

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

答案 4 :(得分:1)

尝试使用std::generate。它可以基于公式为容器生成值

std::vector<int> v(size);
std::generate(v.begin(),v.end(),[n=0]()mutable{return n++;});