如何初始化所有值都相同的2D数组? [英] How to initialize a 2D array with all values same?

查看:55
本文介绍了如何初始化所有值都相同的2D数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用-1作为所有值初始化2D数组.我为此使用了 memset().

I want to initialize a 2D array with -1 as all the value. I used memset() for this.

#include <bits/stdc++.h>
using namespace std;

int dp[100][100];
memset(dp, -1, sizeof(dp));

int dynamicProgramming(some parameters)
{
    //I want to use dp[][] array here
}

int main() {
    cout<<dp[99][99];
    return 0;
}

但是我得到一个错误

prog.cpp:5:7: error: expected constructor, destructor, or type conversion before ‘(’ token
 memset(dp, -1, sizeof(dp));

你能告诉我正确的方法吗?

Can you tell me the correct way to do it?

推荐答案

正如其他人所说,您不能在全局范围内调用 memset .最正确,最清晰的方法可能是

As others have said, you can't call memset in the global scope. The most correct and clear vay is probably going to be something like

#include <iostream>
using namespace std;

const int D1 = 100;
const int D2 = 100;
int dp[D1][D2];

void initializeDp()
{
    for (int i = 0; i < D1; i++) {
        for (int j = 0; j < D2; j++) {
            dp[i][j] = -1;
        }
    }
}

int main() {
    initializeDp();
    cout << dp[D1-1][D2-1];
    return 0;
}

很明显,如果您将全局变量视为一种很好的做法.我个人将使用2d std :: array ,因此它将包含其大小本身

If you count global variables as a good practice, obviously. I personally would use a 2d std::array, so it would contain its size itself

这篇关于如何初始化所有值都相同的2D数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆