我的問題是我們可以使用int a[10][10] = {{0}}
初始化二維數組。在C/C++中將兩個二維數組初始化爲零
根據initialize-large-two-dimensional-array-in-c頂端回答,
int array [ROW][COLUMN] = {0};
這意味着:第一行中的「初始化第一個欄爲0,而所有其他項目,如果他們有靜態存儲時間,即將它們設置爲零。「
但是,檢查C99 Standard 9899:TC3
和C++11 Standard N4296
,我還沒有發現任何支持此答案中提到的正式記錄。
此外,當我嘗試解決以下解決方案的LeetCode 474. Ones and Zeroes
問題時遇到此問題。
// To make question clear:
// It seems that "int dp[m + 1][n + 1] = {{0}}" cannot initilize all elem to 0
// "memset(dp, 0, sizeof dp)" is necessary to pass the OJ test. Any idea?
class Solution {
public:
// m : 0s, n : 1s
int findMaxForm(vector<string>& strs, int m, int n) {
int dp[m + 1][n + 1] = {{0}};
// We will get "Wrong Answer" without memset() function below
memset(dp, 0, sizeof dp);
for (auto& str : strs) {
auto cost = getCost(str);
for (int i = 0; i + cost.first <= m; ++i)
for (int j = 0; j + cost.second <= n; ++j)
dp[i][j] = std::max(dp[i + cost.first][j + cost.second] + 1,
dp[i][j]);
}
int max = 0;
for (int i = 0; i <= m; ++i)
for (int j = 0; j <= n; ++j)
max = std::max(max, dp[i][j]);
return max;
}
private:
pair<int, int> getCost(const string& str) const {
int cnts[] = {0, 0};
for (char c : str) ++cnts[static_cast<char>(c == '1')];
return {cnts[0], cnts[1]};
}
};
N4296是C++ 14和C++ 17之間的草稿,而不是您聲稱的「C++ 11標準」。 –
我誤解了你的問題。 – coderredoc
在++ ++ cnts中強制轉換[static_cast(c =='1')];'是多餘的 –