简体   繁体   中英

c++ trying to initialize values in 2d array

I have created a 2d array called digits and would like to initialize each of the subarrays one by one to make my code clearer. I understand that the following code works:

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

But am wondering why the following doesn't work:

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

The 2nd one is not initialization, it's assignment (of elements of digits ).

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

The element of digits is an array, the raw array can't be assigned as a whole.

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

You could do this with std::array or std::vector , which could be assigned with braced initializer.

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

initialization is far different from assignment. initialization is assigning a value to variable while declaring (invoking constructor) whereas assignment is to declare then assign (invoking assignment operator). to assign correctly you remove brackets and then you use a loop or manually eg:

#include <iostream>
#include <string>
using namespace std;


int main()
{
    string s[2][3];
    string Hi = "Hi there!";

    s[0][0] = "Hello there!";
    //....

    for(int i(0); i < 2; i++)
        for(int j(0); j < 3; j++)
            s[i][j] = Hi;

    for(int i(0); i < 2; i++)
        for(int j(0); j < 3; j++)
            cout << s[i][j] << endl;

    return 0;
}

If you're changing this line for clarity, also consider:

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

Note: Consider . Indentation is a powerful tool, but it can be misused.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM