2012-03-05 176 views
8

我一直在使用下面的向量初始化与代码:: Blocks的价值观和MinGW编译:C++向量初始化

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

之后,我不得不将代码移动到Visual Studio项目(C++)和我试图建立。我得到了以下错误:
本地函数的定义是非法

的Visual Studio编译器不支持这种初始化?
如何更改代码以使其兼容?
我想初始化矢量,并同时用数值填充它,就像数组一样。

+8

这个语法是新的C++ 11,并在Visual C尚不支持++。 – ildjarn 2012-03-05 23:38:30

+2

此语法现在在VS 2013中受支持。来源:[Visual Studio 2013中Visual C++的新增功能](https://msdn.microsoft.com/en-us/library/vstudio/hh409293.aspx) – 2015-02-05 18:17:17

回答

15

Visual C++尚不支持初始化器列表。

,你可以得到这个语法最接近的是使用一个数组来保存初始化然后使用范围构造:

std::array<int, 4> v0_init = { 1, 2, 3, 4 }; 
std::vector<int> v0(v0_init.begin(), v0_init.end()); 
1

另一种方法是boost::assign

#include <boost/assign.hpp> 


using namespace boost::assign; 
vector<int> v; 
v += 1,2,3,4; 
4

你几乎可以做在VS2013中

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

完整示例

#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; 
} 
-2

如果您使用Visual Studio 2015,顺便用list是初始化vector

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

所以,第一个参数指定(3)大小和列表的第二个参数。

+0

我试过了但是,所有元素都具有最后的价值。 – yane 2017-11-26 03:31:57

0

我已经定义一个宏:

#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)) 

,并使用这样的:

init_vector(string, spell, "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"); 

for(auto &a : spell) 
    std::cout<< a <<" ";