gpt4 book ai didi

c++尝试初始化二维数组中的值

转载 作者:搜寻专家 更新时间:2023-10-31 00:29:38 24 4
gpt4 key购买 nike

我已经创建了一个名为 digits 的二维数组,并且想一个一个地初始化每个子数组以使我的代码更清晰。我了解以下代码有效:

string digits[2][5] = { { " - ","| |","   ","| |"," - " },{ " - ","| |","   ","| |"," - " } };

但我想知道为什么以下内容不起作用:

string digits[2][5];
digits[0] = { " - ","| |"," ","| |"," - " };
digits[1] = { " - ", "| |", " ", "| |", " - " };

最佳答案

第二个不是初始化,而是赋值(digits 的元素)。

string digits[2][5];                               // initialization
digits[0] = { " - ","| |"," ","| |"," - " }; // assignment of the 1st element of digits
digits[1] = { " - ", "| |", " ", "| |", " - " }; // assignment of the 2nd element of digits

digits 的元素是一个数组,原始 array不能整体赋值。

Objects of array type cannot be modified as a whole: even though they are lvalues (e.g. an address of array can be taken), they cannot appear on the left hand side of an assignment operator

您可以使用 std::arraystd::vector 来执行此操作,它们可以使用花括号初始化器进行赋值。

std::array<std::array<std::string, 5>, 2> digits;
digits[0] = { " - ","| |"," ","| |"," - " };
digits[1] = { " - ", "| |", " ", "| |", " - " };

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

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