当我将代码从C转换为C++时,我有时会遇到C语言构造,但与C++兼容.通常我想以最少侵入的方式转换代码.但我有一个案例,我发现这很困难:
在C语言中你可以声明一个数组并使用"指示符" 初始化 ...... well ... 部分,其余部分归零(编辑:我在这里写了"留给随机性",第一个):
int data[7] = {
[2] = 7,
[4] = 9,
};
Run Code Online (Sandbox Code Playgroud)
这不是有效的C++代码(幸运的是).所以我将不得不使用不同的策略.
虽然我可以在C++ 11中看到一种非侵入性的方式:
static const map<int,int> data = { {2,7}, {4,9} };
Run Code Online (Sandbox Code Playgroud)
当C++ 11功能尚不可用时,我该怎么办?
data?小智 11
除非阵列的大小完全是疯了,否则你总能做到这一点
int data[7] = {
0,
0,
7, // #2
0,
9 // #4
// the rest will be 0-initialized
};
Run Code Online (Sandbox Code Playgroud)
也适用于编译时
如果没有统一初始化,std::map<int, int>可以使用boost::assign::map_list_of以下方法初始化:
#include <boost/assign/list_of.hpp>
static const std::map<int,int> data = boost::assign::map_list_of(2,7)(4,9);
Run Code Online (Sandbox Code Playgroud)