visual c++矢量初始化
visual c++ vector initialization
我一直在使用以下向量初始化,代码中的值为:Blocks和MingW编译器:
vector<int> v0 {1,2,3,4};
在那之后,我不得不将代码转移到visual studio项目(c++)中,并尝试构建。我得到以下错误:
本地函数定义是非法的
Visual Studio编译器不支持这种初始化
我需要如何更改代码以使其兼容
我想初始化向量,同时用值填充它,就像数组一样。
最接近这种语法的方法是使用数组来保存初始值设定项,然后使用范围构造函数:
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)
指定大小,列表是第二个参数。
相关文章:
- 是否可以初始化不可复制类型的成员变量(或基类)
- C++使用整数的压缩数组初始化对象
- C++初始化基类
- 多成员Constexpr结构初始化
- 复制列表初始化的隐式转换的等级是多少
- 内联映射初始化的动态atexit析构函数崩溃
- 如何在C++中初始化嵌套类中的2个memeber
- 如何声明特征矩阵,然后通过嵌套循环初始化它
- 没有用于初始化C++中的变量模板的匹配构造函数
- 在未初始化映射的情况下,将值插入到映射的映射中
- C++成员初始化
- 为什么在C++中首先初始化成员类
- 同时具有"聚合初始化"和"模板推导"
- 初始化具有非默认构造函数的std::数组项的更好方法
- 是否可以在编译时初始化数组,以便在运行时不会花费时间?
- 我可以使用条件运算符初始化C风格的字符串文字吗
- 在C和C++中初始化结构中的数组
- 标准是否使用多余的大括号(例如 T{{{10}}})定义列表初始化?
- 在函数内部的声明中初始化数组,并在外部使用它
- 继承:构造函数,初始化C++11中基类的类C数组成员