Populate a vector with literal values

Method 1: Use an array and the range constructor

#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>

int main()
{
    typedef std::vector<int> intvec;

    int arr[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30};
    const size_t n = sizeof(arr) / sizeof(int);
    intvec vec1(arr, arr + n);
    
    std::copy(vec1.begin(), vec1.end(), std::ostream_iterator<int>(std::cout, " "));
}

Method 2: Use boost::assign::list_of

#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
#include <boost/assign/list_of.hpp>
#include <boost/range/algorithm/copy.hpp>

int main()
{
    typedef std::vector<int> intvec;

    int arr[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30};
    const size_t n = sizeof(arr) / sizeof(unsigned int);
    
    intvec vec2 = boost::assign::list_of(31)(28)(31)(30)(31)(30)(31)(31)(30)(31)(30);
    
    boost::copy(vec2, std::ostream_iterator<int>(std::cout, " "));
}

Method 3: Use boost::assign

#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
#include <boost/assign/std/vector.hpp>
#include <boost/range/algorithm/copy.hpp>
using namespace boost::assign; // bring 'operator+=()' into scope

int main()
{
    typedef std::vector<int> intvec;

    intvec vec3;
    vec3 += 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30;
    
    boost::copy(vec3, std::ostream_iterator<int>(std::cout, " "));
}

Method 4: Use a C++11 initializer

#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>

int main()
{
    typedef std::vector<int> intvec;

    intvec vec4 = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30};
    
    std::copy(vec4.begin(), vec4.end(), std::ostream_iterator<int>(std::cout, " "));
}

Related