how to find 2d array size in c++

后端 未结 9 824
余生分开走
余生分开走 2020-12-23 12:14

How do I find the size of a 2D array in C++? Is there any predefined function like sizeof to determine the size of the array?

Also, can anyone tell me h

9条回答
  •  失恋的感觉
    2020-12-23 12:52

    The other answers above have answered your first question. As for your second question, how to detect an error of getting a value that is not set, I am not sure which of the following situation you mean:

    1. Accessing an array element using an invalid index:
      If you use std::vector, you can use vector::at function instead of [] operator to get the value, if the index is invalid, an out_of_range exception will be thrown.

    2. Accessing a valid index, but the element has not been set yet: As far as I know, there is no direct way of it. However, the following common practices can probably solve you problem: (1) Initializes all elements to a value that you are certain that is impossible to have. For example, if you are dealing with positive integers, set all elements to -1, so you know the value is not set yet when you find it being -1. (2). Simply use a bool array of the same size to indicate whether the element of the same index is set or not, this applies when all values are "possible".

提交回复
热议问题