Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ vector initialization

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

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

After that I had to move the code to a visual studio project (c++) and I tried to build. I got the following error:
local function definitions are illegal

Visual Studio compiler does not support this kind of initialization?
How do I need to change the code to make it compatible?
I want to initialize vector and fill it with values at the same time, just like an array.

like image 354
cen Avatar asked Mar 05 '12 23:03

cen


2 Answers

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());
like image 70
James McNellis Avatar answered Sep 18 '22 13:09

James McNellis


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;
}
like image 32
CCondron Avatar answered Sep 19 '22 13:09

CCondron