Question

What's the best way for setting an std::vector<int> to a range, e.g. all numbers between 3 and 16?

Was it helpful?

Solution

You could use std::iota if you have C++11 support or are using the 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:

std::vector<int> v;
boost::push_back(v, boost::irange(3, 17));

OTHER TIPS

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

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

std::iota - is useful, but it requires iterator, before creation vector, .... so I take own solution.

#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

Try to use std::generate. It can generate values for a container based on a formula

std::vector<int> v(size);
std::generate(v.begin(),v.end(),[n=0]()mutable{return n++;});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top