Initializer List Not Working with Vector in Visual Studio 2012

Initializer list not working with vector in Visual Studio 2012?

Visual Studio 2012 does not support initializer lists.

Well, it didn't until the November 2012 CTP. Now it does, at least in an alpha state. Granted, this code still won't work in it because they're still putting initializer lists into the standard library itself.

How to init C++ vector/set with array in MS compiler?

std::vector<int> v = {1, 2, 3, 4}; uses an initializer list, not an array. It calls the constructor

vector( std::initializer_list<T> init, 
const Allocator& alloc = Allocator() );

As far as I know, initializer lists are not supported by your compiler version, so if you want to use them, you have to upgrade. As a workaround, you could declare a temporary array and initialize the vector from it.

int[] tmp = {1,2,3,4};
vector<int> v(std::begin(tmp), std::end(tmp));

Issue with initializing Vectors in C++

As I have mentioned that VS2012 does not support initializer_list and hence we get the compilation error. You can use the following to get the almost same thing.

#include<vector>
#include <iterator>
#include<iostream>
using namespace std;

int main() {

int arr[] = {1,2,3,4,5};
const std::vector <int> A(std::begin(arr), std::end(arr));
for(const auto& i: A)
std::cout<<i<<std::endl;
}

vectorstring initialization with {...} is not allowed in VS2012?

The problem

You'll have to upgrade to a more recent compiler version (and standard library implementation), if you'd like to use what you have in your snippet.

VS2012 doesn't support std::initializer_list, which means that the overload among std::vector's constructors, that you are trying to use, simply doesn't exist.

In other words; the example cannot be compiled with VS2012.

  • msdn.com - Support For C++11 Features (Modern C++)

Potential Workaround

Use an intermediate array to store the std::strings, and use that to initialize the vector.

std::string const init_data[] = {
"hello", "world"
};

std::vector<std::string> test (std::begin (init_data), std::end (init_data));

vector initialization, getting an error using code from C++ book

This type of initialization is supported only in C++11, which VS 2010 does not support. You can replace it with old-style initialization. Unfortunately, it would use an extra array, but at least you would be able to get past this point in building your project:

int vectorData[] = {5, 7, 9, 4, 6, 8};
vector<int> v(vectorData, vectorData+6);

Demo.



Related Topics



Leave a reply



Submit