2012-03-05 173 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 <<" ";