[英]Use memset for 2d array at specific row
最近,我了解了C++
。 特別是我了解了memset
function。 但我不知道如何在特定行設置二維數組的值
例子:
int dp[10][10];
// I want to set all values for dp[0] by using memset
// I can do it, by using For loop, like
for (int i = 0; i < 10; i++)
dp[0][i] = 1000;
我試過這個
memset(dp[0], 1000, sizeof dp[0]);
但它運作不佳。
所以我想知道是否有任何方法可以像我希望的那樣使用 memset? 感謝:D
正確的 function 是std::fill_n
: https://en.cppreference.com/w/cpp/algorithm/fill_n
std::fill_n(std::begin(dp[0]), sizeof dp[0] / sizeof dp[0][0], 1000);
或 C++17 或更高版本:
std::fill_n(std::begin(dp[0]), std::size(dp[0]), 1000);
std::fill
也是可能的: https://en.cppreference.com/w/cpp/algorithm/fill
std::fill(std::begin(dp[0]), std::end(dp[0]), 1000);
我會這樣做:
for (auto &i : dp[0]) i = 1000;
這也是最短的版本。
您不能這樣做,因為memset寫入字節。
例如memset( dp[0],3,sizeof( dp[0] ));
將在 dp[0] 的所有 10 個整數中寫入字節 == 3。
所以dp[i] == 0x03030303
for i in 0..9 !
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.