I want to initialize a 2D array with -1 as all the value. I used memset() for this.
#include
using namespace std;
int dp[100]
In practice, in this case, it is possible to write an helping templated function, itself based on simple for-range loops.
One advantage is that is will work for other types of 2D arrays.
#include
template
void init2d (T2d &arr, T val) {
for (auto& row: arr) {
for (auto& i: row) {
i = val;
}
}
}
int main() {
const int n = 5, m = 6;
int a[n][m];
init2d (a, -1);
std::cout << a[n-1][m-1] << "\n";
}
If you want to initialize before main, the simplest way is to rely on STL, e.g. on std::vector or std::array, like this, for a 5x6 matrix:
std::vector> b(5, std::vector (6, -1));