c++ vector initialization

前端 未结 5 833
抹茶落季
抹茶落季 2020-12-20 15:47

I have been using the following vector initialization with values in Code::Blocks and MingW compiler:

vector v0 {1,2,3,4};

A

相关标签:
5条回答
  • 2020-12-20 16:06

    Visual C++ does not yet support initializer lists.

    The closest you can get to this syntax is to use an array to hold the initializer then use the range constructor:

    std::array<int, 4> v0_init = { 1, 2, 3, 4 };
    std::vector<int> v0(v0_init.begin(), v0_init.end());
    
    0 讨论(0)
  • 2020-12-20 16:11

    Another alternative is boost::assign:

    #include <boost/assign.hpp>
    
    
    using namespace boost::assign;
    vector<int> v;
    v += 1,2,3,4;
    
    0 讨论(0)
  • 2020-12-20 16:15

    If you're using Visual Studio 2015, the way to initialize a vector using a list is:

    vector<int> v = {3, (1,2,3)};
    

    So, the first parameter (3) specifies size and the list is the second parameter.

    0 讨论(0)
  • 2020-12-20 16:17

    You can do nearly that in VS2013

    vector<int> v0{ { 1, 2, 3, 4 } };
    

    Full example

    #include <vector>
    #include <iostream>
    int main()
    {    
        using namespace std;
        vector<int> v0{ { 1, 2, 3, 4 } };
        for (auto& v : v0){
            cout << " " << v;
        }
        cout << endl;
        return 0;
    }
    
    0 讨论(0)
  • 2020-12-20 16:24

    I have defined a macro :

    #define init_vector(type, name, ...)\
        const type _init_vector_##name[] { __VA_ARGS__ };\
        vector<type> name(_init_vector_##name, _init_vector_##name + _countof(_init_vector_##name))
    

    and use like this :

    init_vector(string, spell, "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" );
    
    for(auto &a : spell)
      std::cout<< a <<" ";
    
    0 讨论(0)
提交回复
热议问题