I have a valid code in C-style
int arr[10][10] = {0}; // all elements of array are 0
What is the optimal way to do the same for C++ style array?
My idea is
#include <array>
std::array<std::array<int, 10>, 10> arr = {0}; // is it correct?
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It only takes a minute to sign up.
Sign up to join this communityI have a valid code in C-style
int arr[10][10] = {0}; // all elements of array are 0
What is the optimal way to do the same for C++ style array?
My idea is
#include <array>
std::array<std::array<int, 10>, 10> arr = {0}; // is it correct?
I feel this question is more suited for stack overflow, but I'll answer it anyway. In c++ the preferred way to do this is:
std::array<std::array<int, 10>, 10> arr = {}; // Without the 0
Also remember that static
variables are zero-initialised anyway, so you wouldn't need to do that.
Because this is code review, I would suggest using a typedef
to replace std::array<std::array<int, 10>, 10>
to make your code more readable.
EDIT: As pointed out in the comments, using
is much more powerful than typedef
and more modern-c++ ish and one should preferably use it rather than typedef
. It supports type aliasing templates and all other cool stuff, which is why it is preferable to use. ( Though never use using namespace ...;
)
using
instead of typedef
as we want to use modern c++ practices.
\$\endgroup\$
Mar 1, 2021 at 16:07