2D array values C++

2020-01-30 11:58发布

I wanted to declare a 2D array and assign values to it, without running a for loop.

I thought I could used the following idea

int array[5] = {1,2,3,4,5};

Which works fine to initialize the 2D array as well. But apparently my compiler doesn't like this.

/*
 1   8  12  20  25
 5   9  13  24  26
*/

#include <iostream.h>

int main()
{
    int arr[2][5] = {0};   // This actually initializes everything to 0.
    arr [1] [] = {1,8,12,20,25}; // Line 11
    arr [2] [] = {5,9,13,24,26};
    return 0;
}

J:\CPP\Grid>bcc32.exe Grid.cpp

Borland C++ 5.5.1 for Win32 Copyright (c) 1993, 2000 Borland

Grid.cpp:

Error E2188 Grid.cpp 11: Expression syntax in function main()

Error E2188 Grid.cpp 12: Expression syntax in function main()

Warning W8004 Grid.cpp 14: 'arr' is assigned a value that is never used in funct ion main()

* 2 errors in Compile *

Please help as to what is the right way to initialize the 2d array with my set of values.

5条回答
Evening l夕情丶
2楼-- · 2020-01-30 12:25

The proper way to initialize a multidimensional array in C or C++ is

int arr[2][5] = {{1,8,12,20,25}, {5,9,13,24,26}};

You can use this same trick to initialize even higher-dimensional arrays if you want.

Also, be careful in your initial code - you were trying to use 1-indexed offsets into the array to initialize it. This didn't compile, but if it did it would cause problems because C arrays are 0-indexed!

查看更多
老娘就宠你
3楼-- · 2020-01-30 12:25

One alternative is to represent your 2D array as a 1D array. This can make element-wise operations more efficient. You should probably wrap it in a class that would also contain width and height.

Another alternative is to represent a 2D array as an std::vector<std::vector<int> >. This will let you use STL's algorithms for array arithmetic, and the vector will also take care of memory management for you.

查看更多
混吃等死
4楼-- · 2020-01-30 12:28

Just want to point out you do not need to specify all dimensions of the array.

The leftmost dimension can be 'guessed' by the compiler.

#include <stdio.h>
int main(void) {
  int arr[][5] = {{1,2,3,4,5}, {5,6,7,8,9}, {6,5,4,3,2}};
  printf("sizeof arr is %d bytes\n", (int)sizeof arr);
  printf("number of elements: %d\n", (int)(sizeof arr/sizeof arr[0]));
  return 0;
}
查看更多
欢心
5楼-- · 2020-01-30 12:28

int iArray[2][2] = {{1, 2}, {3, 4}};

Think of a 2D array as an array of arrays.

查看更多
对你真心纯属浪费
6楼-- · 2020-01-30 12:44

Like this:

int main()
{
    int arr[2][5] =
    {
        {1,8,12,20,25},
        {5,9,13,24,26}
    };
}

This should be covered by your C++ textbook: which one are you using?

Anyway, better, consider using std::vector or some ready-made matrix class e.g. from Boost.

查看更多
登录 后发表回答