gpt4 book ai didi

c++ - 在 C++ 中初始化二维数组

转载 作者:行者123 更新时间:2023-12-05 06:54:48 28 4
gpt4 key购买 nike

我正在尝试在以下代码中初始化一个二维数组 -

int main(void)
{
int arr[][5] = {
[0][1] : 1, [0][0] : 2, [0][2] : 3,
};
cout<<a[0][0]<<" "<<a[0][1]<<endl;

return 0;
}

但是编译器给我以下错误-

./2d-arr.cpp: In function ‘int main()’:
./2d-arr.cpp:7:4: error: expected identifier before numeric constant
[0][1] : 1, [0][0] : 2, [0][2] : 3,
^
./2d-arr.cpp: In lambda function:
./2d-arr.cpp:7:6: error: expected ‘{’ before ‘[’ token
[0][1] : 1, [0][0] : 2, [0][2] : 3,
^
./2d-arr.cpp: In function ‘int main()’:
./2d-arr.cpp:7:6: error: no match for ‘operator[]’ (operand types are ‘main()::<lambda()>’ and ‘int’)
./2d-arr.cpp:7:10: error: expected ‘}’ before ‘:’ token
[0][1] : 1, [0][0] : 2, [0][2] : 3,
^
./2d-arr.cpp: At global scope:
./2d-arr.cpp:9:2: error: ‘cout’ does not name a type
cout<<a[0][0]<<" "<<a[0][1]<<endl;
^~~~
./2d-arr.cpp:11:2: error: expected unqualified-id before ‘return’
return 0;
^~~~~~
./2d-arr.cpp:12:1: error: expected declaration before ‘}’ token
}
^

然而,如果我用“=”替换“:”并用 gcc 编译它,它运行良好。我的理解是
在谷歌搜索之后,错误消息是我们无法像在 C 中那样初始化数组。
是否可以对上面的代码进行任何处理以使其适用于 C++?

最佳答案

我从 here 中找到了以下代码快照
其中声明上述初始化对 C++ 无效。

struct A { int x, y; };
struct B { struct A a; };
struct A a = {.y = 1, .x = 2}; // valid C, invalid C++ (out of order)
**int arr[3] = {[1] = 5}; // valid C, invalid C++ (array)**
struct B b = {.a.x = 0}; // valid C, invalid C++ (nested)
struct A a = {.x = 1, 2}; // valid C, invalid C++ (mixed)

不可能像在 C 中那样在 C++ 中使用 [] 进行指定初始化。

关于c++ - 在 C++ 中初始化二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65460031/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com