visual c++矢量初始化

visual c++ vector initialization

本文关键字:初始化 c++ visual      更新时间:2023-10-16

我一直在使用以下向量初始化,代码中的值为:Blocks和MingW编译器:

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

在那之后,我不得不将代码转移到visual studio项目(c++)中,并尝试构建。我得到以下错误:
本地函数定义是非法的

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

Visual C++还不支持初始值设定项列表。

最接近这种语法的方法是使用数组来保存初始值设定项,然后使用范围构造函数:

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

在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;
}

另一种选择是boost::assign:

#include <boost/assign.hpp>

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

我定义了一个宏:

#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 <<" ";

如果使用Visual Studio 2015,使用list初始化vector的方法是:

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

因此,第一个参数(3)指定大小,列表是第二个参数。